Min/Max across an array of objects

Posted by graham.reeds on Stack Overflow See other posts from Stack Overflow or by graham.reeds
Published on 2010-03-13T17:27:57Z Indexed on 2010/03/13 17:35 UTC
Read the original article Hit count: 367

Filed under:

It has been done to death pretty much, here on SO and around the 'Net. However I was wondering if there was a way to leverage the standard min/max functions of:

Array.max = function(array) {
    return Math.max.apply(Math, array);
};

Array.min = function(array) {
    return Math.min.apply(Math, array);
};

So I can search across an array of objects of say:

function Vector(x, y, z) { this.x = x; this.y = y; this.z = z; }
var ArrayVector = [ /* lots of data */ ];
var min_x = ArrayVector.x.min(); // or
var max_y = ArrayVector["y"].max();

Currently I have to loop through the array and compare the object values manually and craft each one to the particular need of the loop. A more general purpose way would be nice (if slightly slower).

© Stack Overflow or respective owner

Related posts about JavaScript