JavaScript objects allow you to easily store lots of data in a compact manner as attribute-value pairs. Often web developers also create Array of JS objects to store a number of JavaScript objects in one place. Sometimes you may need to find max attribute value in array of JS objects. In this article, we will learn how to find max value of attribute in array of JS objects.
How to Find Max Value of Attribute in Array of JS Objects
Let us say you have the following JavaScript object that contains an array of objects where each object contains two attribute-value pairs – one is a date and the other is the sale amount on that date.
var data = [ { "dt": "8/11/2022", "sale": 200 }, { "dt": "8/12/2022", "sale": 250 }, { "dt": "8/13/2022", "sale": 150 }, { "dt": "8/14/2022", "sale": 300 } ]
You can easily get the maximum attribute value using the apply() function.
Math.max.apply(Math, array.map(function(o) { return o.sale; }))
In the above code, apply() method applies the Math.max() function on the array of sale values returned using array.map() method.
Alternatively, you can also use a more compact way of achieving the same thing using arrow functions.
Math.max(...array.map(o => o.sale))
If the above commands are complicated for you, then you can try using reduce() method as shown below.
const max = data.reduce(function(prev, current) { return (prev.sale > current.sale) ? prev : current })
The reduce method iterates through the array of JS objects comparing sale values of consecutive objects to return the higher value. By the time, reduce method has traversed the entire array, max variable will contain the maximum attribute value.
Here is a more compact way to use the same code using arrow functions.
const max = data.reduce((prev, current) => (prev.sale > current.sale) ? prev : current)
In this article, we have learnt a couple of simple ways to get max value of attribute in array of JS objects. Out of them, the one with reduce() method is faster than using apply() method because the time complexity of using reduce() method here is O(n) while that of using apply() method is O(2n). So it is suitable if you have large array of JS objects to work with.
Also read:
How to Get Last Item in JS Array
How to Check if Variable is Object in JS
How to Check if Browser Tab is Active in JS
How to Find DOM Element Using Attribute in JS
How to Generate Hash from String in JS
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.