How to use Array.reduce() Method In Javascript
Array.reduce() is a powerful method in JavaScript used to reduce the elements of an array to a single value. It executes a provided function for each value of the array and accumulates a single result.
Syntax:
Array.reduce(callbackFunction, initialValue)
Example: The below code explains the use of the reduce() method to get the index of the max value in an array of objects.
Javascript
function indexOfMax(arr, prop) { return arr.reduce( (maxIndex, current, currentIndex, array) => { return current[prop] > array[maxIndex][prop] ? currentIndex : maxIndex; }, 0); } const people = [ { name: 'Alice' , age: 30 }, { name: 'Bob' , age: 40 }, { name: 'John' , age: 35 } ]; const maxAgeIndex = indexOfMax(people, 'age' ); console.log( "Index of person with maximum age:" , maxAgeIndex); |
Output
Index of person with maximum age: 1
How to Get Index of the Max Value in Array of Objects ?
When dealing with arrays of objects in JavaScript, it’s common to need the index of the object with the maximum value based on a certain property.
Below are the approaches to get the index of the max value in an array of objects:
Table of Content
- Using a Loop
- Using Array.reduce() Method
Contact Us