I\'m looking for a really quick, clean and efficient way to get the max \"y\" value in the following JSON slice:
[
{
\"x\": \"8/11/2009\",
\"y\": 0
I'd like to explain the terse accepted answer step-by-step:
var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];
// array.map lets you extract an array of attribute values
var xValues = objects.map(function(o) { return o.x; });
// es6
xValues = Array.from(objects, o => o.x);
// function.apply lets you expand an array argument as individual arguments
// So the following is equivalent to Math.max(3, 1, 2)
// The first argument is "this" but since Math.max doesn't need it, null is fine
var xMax = Math.max.apply(null, xValues);
// es6
xMax = Math.max(...xValues);
// Finally, to find the object that has the maximum x value (note that result is array):
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });
// Altogether
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];
// es6
xMax = Math.max(...Array.from(objects, o => o.x));
maxXObject = objects.find(o => o.x === xMax);
document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');
Further information:
if you (or, someone here) are free to use lodash
utility library, it has a maxBy function which would be very handy in your case.
hence you can use as such:
_.maxBy(jsonSlice, 'y');
To find the maximum y
value of the objects in array
:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
ES6 solution
Math.max(...array.map(function(o){return o.y;}))
For more details see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
Or a simple sort! Keeping it real :)
array.sort((a,b)=>a.y<b.y)[0].y
var max = 0;
jQuery.map(arr, function (obj) {
if (obj.attr > max)
max = obj.attr;
});