![]() |
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 LoopThis 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
Output
Index of employee with highest salary: 1 Using Array.reduce() MethodArray.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
Output
Index of person with maximum age: 1 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |