How to use Array.prototype.sort() In Javascript
The Array.prototype.sort() method sorts an array in place based on a specified comparator function. To find the maximum value of an attribute in an array of objects, sort the array in descending order using the attribute as the sorting key and access the first element.
Example :
const array = [
{ id: 1, value: 10 },
{ id: 2, value: 20 },
{ id: 3, value: 15 }
];
array.sort((a, b) => b.value - a.value);
const max = array[0].value;
console.log(max); // 20
Output
20
How to search the max value of an attribute in an array object ?
In this article, we will learn how to search for the maximum value of an attribute in an array object. The maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method by using the Math.max.apply() method.
These are the following methods:
Table of Content
- Using Loop
- Using Math.max.apply()
- Using reduce() method
- Using Lodash _.sortBy() method
- Using Array.prototype.sort()