如何在Javascript中的复杂对象数组中找到最小/最大值

How to find min/max value in Array of complex objects in Javascript?

本文关键字:最大值 数组 对象 Javascript 复杂      更新时间:2023-09-26

假设我们有一个数组:

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"
}];

我们想找到数组中对象的所有数值性质的minmax(这里是penicillinstreptomycinneomycin),假设值可以为空/不存在。

如何在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);
};

如果数组存在并简单计算,则会用值填充数组。

希望这能有所帮助。