Open In App

How to Get Index of the Max Value in Array of Objects ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using a Loop

This approach iterates through the array of objects using a simple for loop. It keeps track of the index of an object with the maximum value based on the specified property.

Example: The below code uses a for loop to iterate over the array of objects and get the index of the max value.

Javascript




function indexOfMax(arr, prop) {
    let max = -Infinity;
    let index = -1;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][prop] > max) {
            max = arr[i][prop];
            index = i;
        }
    }
    return index;
}
 
const employees = [
    { name: 'John', salary: 50000 },
    { name: 'Alice', salary: 70000 },
    { name: 'Bob', salary: 60000 }
];
 
const maxSalaryIndex =
    indexOfMax(employees, 'salary');
console.log("Index of employee with highest salary:",
    maxSalaryIndex);


Output

Index of employee with highest salary: 1

Using Array.reduce() Method

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads