How to use reduce method In Javascript
The reduce method iterates through array elements, comparing each with the target value. It returns the index when the value is found, updating the accumulator; otherwise, it returns -1.
Example: In this example, the reduce method iterates over each item in the array. If the current item matches the value we’re searching for and the accumulator is still -1 (meaning the item hasn’t been found yet), it returns the current index.
const fruits = ['apple', 'banana', 'cherry', 'orange'];
const value = 'cherry';
const index = fruits.reduce((acc, item, currentIndex) => {
if (item === value && acc === -1) {
return currentIndex;
}
return acc;
}, -1);
console.log(index);
Output
2
Find the Array Index with a Value in JavaScript
Finding the index of a specific value in an array in JavaScript involves searching through the array’s elements to locate the position of the desired value. This index serves as a reference point for accessing or manipulating the value within the array.
Example 1:
Input: ['apple', 'banana', 'cherry', 'orange']
N = 'cherry'
Output: 2
Explanation: The index of the word cherry is 2
These are the following approaches by using these we can find the Array Index with a Value:
Table of Content
- Using indexOf() method
- Using findIndex() method
- Using for loop
- Using Lodash _.findIndex() Method
- Using reduce method