Min / Max over an array of objects

This was done to death to a large extent, here on SO and around the Web. However, I was wondering if the standard min / max functions could be used:

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

So, I can do a search on an array of objects:

 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 go through the array and compare the values โ€‹โ€‹of the objects manually and process each of them with the specific need of the loop. A more general way would be nice (if a little slower).

+6
javascript
source share
1 answer

You can make some changes to the Array.min and max methods to accept the property name, extract this property of each object in the array using Array.prototype.map and the maximum or minimum value of these extracted values:

 Array.maxProp = function (array, prop) { var values = array.map(function (el) { return el[prop]; }); return Math.max.apply(Math, values); }; var max_x = Array.maxProp(ArrayVector, 'x'); 

I just want to mention that the Array.prototype.map method will be available in almost all modern browsers, and it is part of the ECMAScript 5th Edition Specification , but Internet Explorer does not have it, however you can easily enable an implementation similar to that found in the Mozilla Developer Center .

+6
source share

All Articles