![]() |
A JavaScript program searches an element in an array by iterating through each item and comparing it with the target value. If found, it returns the index; otherwise, it returns -1, indicating absence. Following are the ways to search for an element in an array: Table of Content Approach 1: Using Recursive ApproachThe recursive approach in JavaScript for binary search involves dividing the array recursively until finding the target element or exhausting the search space, returning the element’s index or -1 accordingly. Example: The function recursively applies binary search to locate the target element within a sorted array, returning its index if found, or -1 if not present, with efficient time complexity.
Output The index of 30 is: 2 Approach 2: Using Array.reduce() methodThe binary search is implemented with Array.reduce() iterates through the array, accumulating results. It returns the index of the target element or -1 if not found, with linear time complexity. Example: The function uses Array.reduce to search for the target element within an array, returning its index if found, or -1 if not present, with linear time complexity.
Output The index of Redux is: 4 Approach 3: Using a for loop:Using a for loop, iterate through the array elements, comparing each element to the target. If a match is found, return true; otherwise, return false after iterating through all elements. Example: In this example The searchElement function iterates through an array to find a target element and returns its index if found, otherwise returns -1.
output: The index of 30 is: 2 Approach 4: Using Array.indexOf():To search an element in an array using `Array.indexOf()`, provide the element to search for as an argument. It returns the index of the first occurrence of the element, or -1 if not found. Example: In this example we searches for the element “3” within the array using Array.indexOf(), returning its index. Output: 2 (indexing starts from 0).
Output 2 Approach 5: Using includesUsing the includes method, you can check if an array contains a specific element. This method returns true if the element is found and false otherwise. It provides a simple and readable way to verify the presence of an element within an array. Example: in this example we are searching if certain elements present in array or not.
Output true false |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |