Friday, 13 September 2013

Get max and min of object values from JavaScript array

Get max and min of object values from JavaScript array

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( minX < a[x].x )
maxX = a[x].x;
}
Seems a bit clumsy. Is there a more elegant way, perhaps using dojo?

No comments:

Post a Comment