Get max and min of object values from JavaScript array

Martlark picture Martlark · Sep 14, 2013 · Viewed 9.2k times · Source

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?

Answer

dc5 picture dc5 · Sep 14, 2013

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);