Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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( maxX < a[x].x )
     maxX = a[x].x;
}

Seems a bit clumsy. Is there a more elegant way, perhaps using dojo?

like image 646
Martlark Avatar asked Sep 14 '13 05:09

Martlark


1 Answers

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);
like image 128
dc5 Avatar answered Oct 10 '22 08:10

dc5