To find the maximum y value of the objects in array:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
or in more modern JavaScript:
Math.max(...array.map(o => o.y))
Warning:
This method is not advisable, it is better to use reduce. With a large array, Math.max will be called with a large number of arguments, which can cause stack overflow.
To find the maximum y value of the objects in array:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
or in more modern JavaScript:
Math.max(...array.map(o => o.y))
Warning:
This method is not advisable, it is better to use reduce. With a large array, Math.max will be called with a large number of arguments, which can cause stack overflow.
Find the object whose property "Y" has the greatest value in an array of objects
One way would be to use Array reduce..
const max = data.reduce(function(prev, current) {
return (prev && prev.y > current.y) ? prev : current
}) //returns object
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
- http://caniuse.com/#search=reduce (IE9 and above)
If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.
const max = data.reduce((prev, current) => (prev && prev.y > current.y) ? prev : current)
Note that if you have multiple objects sharing the same max value, it will only return the first matched object.
ES6 Find the maximum number of an array of objects?
If you want to use ES6 and get this done in one line:
const shots = [
{id: 1, amount: 2},
{id: 2, amount: 4},
{id: 3, amount: 52},
{id: 4, amount: 36},
{id: 5, amount: 13},
{id: 6, amount: 33}
];
shots.reduce((acc, shot) => acc = acc > shot.amount ? acc : shot.amount, 0);
Can replace the ternary with a Math.max(acc, shot.amount), along with many other multiple methods. The issue with the reduce function you produced on SO, your reducer accumulator/initial value (0) was placed in the wrong spot.
More on reddit.comMap or Reduce to calculate max value from JSON
[Javascript] In array of objects, find max value of a specific property (weight of guy), but then return a different property (guy's name) of that object with that max?
Are you okay with sorting the array?
Dudes = Dudes.sort(function(a, b){
return a.weight < b.weight;
});
console.log(Dudes[0].fName);
More on reddit.com