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.
In this example, we use reduce()
method with ternary operator (?
) to get an object with a minimum number
property value from array
of objects.
xxxxxxxxxx
1
var array = [
2
{ id: 1, number: 20 },
3
{ id: 2, number: 30 },
4
{ id: 3, number: 10 }
5
];
6
7
var min = array.reduce(function(previous, current) {
8
return previous.number < current.number ? previous : current;
9
});
10
11
console.log(JSON.stringify(min)); // {"id":3,"number":10}
In this example, we use reduce()
method with ternary operator (?
) to get an object with a maximum number
property value from array
of objects.
xxxxxxxxxx
1
var array = [
2
{ id: 1, number: 20 },
3
{ id: 2, number: 30 },
4
{ id: 3, number: 10 }
5
];
6
7
var max = array.reduce(function(previous, current) {
8
return previous.number > current.number ? previous : current;
9
});
10
11
console.log(JSON.stringify(max)); // {"id":2,"number":30}