What is the best way to get the maximum and minimum values from a JavaScript array of objects?
Given:
var a = [{x:1,y:0},{x:-1,y:10},{x:12,y:20},{x:61,y:10}];
var minX = Infinity, maxX = -Infinity;
for( var x in a ){
if( minX > a[x].x )
minX = a[x].x;
if( maxX < a[x].x )
maxX = a[x].x;
}
Seems a bit clumsy. Is there a more elegant way, perhaps using dojo?
It won't be more efficient, but just for grins:
var minX = Math.min.apply(Math, a.map(function(val) { return val.x; }));
var maxX = Math.max.apply(Math, a.map(function(val) { return val.x; }));
Or if you're willing to have three lines of code:
var xVals = a.map(function(val) { return val.x; });
var minX = Math.min.apply(Math, xVals);
var maxX = Math.max.apply(Math, xVals);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With