How do i use Math.max with an array of objects?
One more way, I think it is more beautiful. By using spread:
Math.max(...array.map((i) => i.x));
You'll have to extract the properties from the objects yourself:
var maximum = Math.max.apply(Math, myArr.map(function(o) { return o.x; }));
That uses .map()
to iterate through the elements of the array and return the value of the "x" property. That result array is then passed as the arguments to Math.max()
.
Now that =>
functions are widely available it'd be a little shorter as so:
var maximum = Math.max.apply(Math, myArr.map(o => o.x));
Still doing pretty much the exact same thing of course.
var myArr = [{x:100,y:200},{x:200,y:500}];
function sortByKeyDesc(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
});
}
console.log(sortByKeyDesc(myArr, "x")[0].x);
first sort by key value in descending order and then get the first object's x
property