如何在Javascript中的复杂对象数组中找到最小/最大值
How to find min/max value in Array of complex objects in Javascript?
假设我们有一个数组:
var antibiotics = [{
bacteria: "Mycobacterium tuberculosis",
penicillin: 800,
streptomycin: 5,
neomycin: 2,
gram: "negative"
}, {
bacteria: "Salmonella schottmuelleri",
penicillin: 10,
streptomycin: 0.8,
neomycin: 0.09,
gram: "negative"
}, {
bacteria: "Proteus vulgaris",
penicillin: 3,
streptomycin: 0.1,
neomycin: 0.1,
gram: "negative"
}, {
bacteria: "Klebsiella pneumoniae",
penicillin: 850,
gram: "negative"
}];
我们想找到数组中对象的所有数值性质的min
和max
(这里是penicillin
、streptomycin
和neomycin
),假设值可以为空/不存在。
如何在JavaScript中从对象数组中聚合此类数据?
您可以使用Array.prototype.map()
提取所需的值,然后作为参数传递给Math.max()
或Math.min()
。
Math.max.apply(Math, values);
不幸的是,JS标准库不提供Array.max
或"pull"(=collect)函数,但有许多库提供,例如下划线:
maxPenicillin = _.max(_(antibiotics).pluck('penicillin')))
如果你不喜欢库,这些功能很简单:
Array.prototype.max = function() {
return this.reduce(function(a, b) {
return a > b ? a : b;
})
}
Array.prototype.pluck = function(prop) {
return this.map(function(x) {
return x[prop];
})
}
maxPenicillin = antibiotics.pluck('penicillin').max()
但实际上,你为什么要重新发明轮子?只要使用图书馆。
Upd:如果我正确解读了你的评论,你正在寻找这样的东西:
var values = {};
_.each(antibiotics, function(x) {
_.each(x, function(v, k) {
if(!isNaN(v))
values[k] = (values[k] || []).concat([v]);
})
})
var minmax = {};
_.each(values, function(v, k) {
minmax[k] = [_.min(v), _.max(v)]
})
结果:
{"penicillin":[3,850],"streptomycin":[0.1,5],"neomycin":[0.09,2]}
这样就可以了。
http://jsfiddle.net/vgW4v/
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
如果数组存在并简单计算,则会用值填充数组。
希望这能有所帮助。
相关文章:
- 在Javascript数组中查找绝对最大值
- 按最大值获取数组索引
- 从 JavaScript 中的数组中获取最大值和最小值
- 使用函数从数组中查找最小值和最大值
- 如何在JavaScript中从数组中获取最大值
- 在JavaScript多维数组中查找每个x值的最大值
- 从一个值数组中获取多个最大值
- 如何获取数组中包含最大值的两个对象
- 返回数组中最大值的索引
- 如何找到最大值并从数组中返回它
- 数组中的最大值(值是数组对象中的属性)
- 在多维数组 JavaScript 或 coffeescript 中获取最大值
- 在稀疏 JavaScript 数组中查找最大值
- 在带有对象的数组中查找最小值、最大值
- JavaScript 中的最大公共数组切片
- 如何确定 JSON 对象数组中特定字段的最大值
- 如何在 JavaScript 中的数组列表中查找最大的数组值
- 从父数组中获取长度最大的数组
- JavaScript:最大的数组不工作
- 如何获得最小和最大的数组在javascript