If you want to do it the old fashioned way:
function arrayMax(arr, key){
var m = -Infinity,
cur,
i;
for(i=0; i<arr.length; i++){
cur = arr[i][key]
if(cur > m){
m = cur;
}
}
return m;
}
This function takes an array of objects as the first argument and a key as the second. It iterates over the array and returns the largest value found for the given key.
In your case, you would call it like this:
var maximum = arrayMax(myArr, "x");
Notice that, unlike Math.max, this is resilient to the case where one (or more) of the objects does not have that key defined, so that:
arrayMax([{y:200}, {x:100, y:100}, {x:300, y:400}], "x");
Will return 300
, whereas Math.max
returns NaN
(on Google chrome, at least). Worst case scenario (none of the objects has the key defined), the arrayMax
function returns -Infintity
.
If you want to return the object that has the largest value instead of simply returning the value, you can easily modify the function to do so:
function arrayMax(arr, key){
var m = -Infinity,
o = null,
cur,
curv,
i;
for(i=0; i<arr.length; i++){
cur = arr[i]
curv = cur[key]
if(curv > m){
m = curv;
o = cur;
}
}
return o;
}