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