Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min/Max across an array of objects

Tags:

javascript

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).

like image 815
graham.reeds Avatar asked Mar 13 '10 17:03

graham.reeds


People also ask

How do you find the minimum value of an array of objects?

Using map(), Math, and the spread operator map() function, we take all of our Y values and insert them into a new Array of Numbers. Now that we have a simple Array of numbers, we use Math. min() or Math. max() to return the min/max values from our new Y value array.

Can you use math min on an array?

Example 2: Get a minimum value from an arrayThe Math. min() method compares the variable min with all elements of the array and assigns the minimum value to min .

Can you use math Max on an array?

Example 2: Get a maximum value from an array Initially, the variable max stores the first element of the array. The Math. max() method compares the variable max with all elements of the array and assigns the maximum value to max .


1 Answers

You could make some changes to your Array.minand max methods to accept a property name, extract that property of each object in the array, with the help of Array.prototype.map, and the max or min value of those 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 on almost all modern browsers, and it is part of the ECMAScript 5th Edition Specification, but Internet Explorer doesn't have it, however you can easily include an implementation like the found on the Mozilla Developer Center.

like image 178
Christian C. Salvadó Avatar answered Nov 03 '22 07:11

Christian C. Salvadó