最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - MinMax across an array of objects - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Mar 13, 2010 at 17:27 graham.reedsgraham.reeds 16.5k17 gold badges76 silver badges138 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论