How to useArray.reduce() in Javascript
Using Array.reduce(), the function iterates through the array, accumulating an index where the object’s specified key matches the given value. If found, it returns the index; otherwise, it returns -1, indicating the object was not found.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example: In this example The findIndexByKeyValue function searches an array of objects for a specific key-value pair and returns the index of the first matching object.
function findIndexByKeyValue(arr, key, value) {
return arr.reduce((index, obj, i) => (obj[key] === value ? i : index), -1);
}
let array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }];
let index = findIndexByKeyValue(array, 'name', 'Bob');
console.log(index); // 1
Output
1
JavaScript Program to Find Index of an Object by Key and Value in an Array
Finding the index of an object by key and value in an array involves iterating through the array and checking each object’s key-value pair. Once a match is found, its index is returned. If no match is found, -1 is returned.
Example:
arr = [ { course: "DevOps", price: 11999 }, { course: "GATE", price: 6999 }, { course: "ML & DS", price: 5999 }, { course: "DSA", price: 3999 }, ]; Input: key = "course"; value = "DSA"; Output: 3 Explanation: name : DSA object is at 3rd index in the array.
Table of Content
- Using JavaScript for Loop and If Condition
- Using findIndex() Method
- Using Array map() and indexOf Methods
- Using Array some() Method
- Using Array.reduce()
So let’s see each of the approaches with its implementation.