Open In App

JavaScript Program to Search an Element in an Array

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Approach 1: Using Recursive Approach

The 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.

Javascript
function SearchingFunction(arr, target, low = 0, high = arr.length - 1) {
    if (low > high) return -1;

    let mid = Math.floor((low + high) / 2);

    if (arr[mid] === target) return mid;
    else if (arr[mid] < target)
        return SearchingFunction(arr, target, mid + 1, high);
    else
        return SearchingFunction(arr, target, low, mid - 1);
}

const array = [10, 20, 30, 40, 50, 60];
const targetElement = 30;
const result = SearchingFunction(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);

Output
The index of 30 
is: 2

Approach 2: Using Array.reduce() method

The 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.

Javascript
function SearchingFunction(arr, target) {
    return arr.reduce((acc, val, index) => {
        if (acc !== -1) return acc;
        if (val === target) return index;
        return -1;
    }, -1);
}

const array = ["HTML", "CSS", "Javascript", "React", "Redux", "Node"];
const targetElement = "Redux";
const result = SearchingFunction(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);

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.

JavaScript
function searchElement(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === target) {
            return i; // Return index if found
        }
    }
    return -1; // Return -1 if not found
}

const array = [10, 20, 30, 40, 50, 60];
const targetElement = 30;
const result = searchElement(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);

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).

JavaScript
let array = [1, 2, 3, 4, 5];
let searchElement = 3;
let index = array.indexOf(searchElement); 
// Returns index 2 (indexing starts from 0)
console.log(index); 

Output
2




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads