How to useArray.reduce() method in Javascript

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

JavaScript Program to Search an Element in an Array

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

  • Using Recursive Approach
  • Using Array.reduce() method
  • Using a for loop:
  • Using Array.indexOf():
  • Using includes

Similar Reads

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

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

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

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

Approach 5: Using includes

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