EN
JavaScript - compare array of objects to get min / max
0
points
In this article, we would like to show you how to compare an array of objects to get the min/max value of a property in JavaScript.
1. Minimum
In this example, we use reduce() method with ternary operator (?) to get an object with a minimum number property value from array of objects.
// ONLINE-RUNNER:browser;
var array = [
{ id: 1, number: 20 },
{ id: 2, number: 30 },
{ id: 3, number: 10 }
];
var min = array.reduce(function(previous, current) {
return previous.number < current.number ? previous : current;
});
console.log(JSON.stringify(min)); // {"id":3,"number":10}
2. Maximum
In this example, we use reduce() method with ternary operator (?) to get an object with a maximum number property value from array of objects.
// ONLINE-RUNNER:browser;
var array = [
{ id: 1, number: 20 },
{ id: 2, number: 30 },
{ id: 3, number: 10 }
];
var max = array.reduce(function(previous, current) {
return previous.number > current.number ? previous : current;
});
console.log(JSON.stringify(max)); // {"id":2,"number":30}