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?
You could use
sort
. This method modifies the original array, so you might need to clone it :You can use
map
functionality, but it is pretty much just a syntactic sugar aroundfor
. Any solution usingreduce
would be twice as slow as your "naive" because it would iterate array once for min value and once more for max. Your current solution is pretty much the best you can have in terms of performance. All you can do is to shave off some more lookups by caching them.Another idea is to calculate max/min by reducing the values to one value. This is exactly same as your version in terms of time complexity but a bit different way to think. (
reduce()
is supported since JavaScript 1.8.)I know its a little too late, but for newer users you could use lodash. It makes the stuff a lot simpler.
Or you could use .sort() to the task as procrastinator explained.
Use this example
It won't be more efficient, but just for grins:
Or if you're willing to have three lines of code: