跨对象数组的最小值/最大值

时间:2022-07-28 20:14:28

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:

它已经完成了死亡,在SO和围绕'网络。但是我想知道是否有办法利用标准的最小/最大函数:

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

目前,我必须循环遍历数组并手动比较对象值,并根据循环的特定需要制作每个对象值。更通用的方式会很好(如果稍慢)。

1 个解决方案

#1


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.min和max方法进行一些更改以接受属性名称,在Array.prototype.map的帮助下提取数组中每个对象的属性,以及这些提取值的最大值或最小值:

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.

我只想提一下,几乎所有现代浏览器都可以使用Array.prototype.map方法,它是ECMAScript第5版规范的一部分,但是Internet Explorer没有它,但是你可以很容易地包含像在Mozilla开发人员中心找到。

#1


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.min和max方法进行一些更改以接受属性名称,在Array.prototype.map的帮助下提取数组中每个对象的属性,以及这些提取值的最大值或最小值:

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.

我只想提一下,几乎所有现代浏览器都可以使用Array.prototype.map方法,它是ECMAScript第5版规范的一部分,但是Internet Explorer没有它,但是你可以很容易地包含像在Mozilla开发人员中心找到。