简体   繁体   中英

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

Say we have an array:

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

And we want to find min and max of all numerical properties of objects in array ( penicillin , streptomycin and neomycin here) assuming values can be null/absent.

How to aggregate such data from an array of objects in JavaScript?

您可以使用Array.prototype.map()提取所需的值,然后将其作为参数传递给Math.max()Math.min()

Math.max.apply(Math, values);

Unfortunately, JS standard library doesn't provide Array.max or a "pluck" (=collect) function, but there are many libraries that do, eg underscore:

maxPenicillin = _.max(_(antibiotics).pluck('penicillin')))

If you don't like libraries, these function are easy:

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

but really, why would you want to reinvent the wheel? Just use a library.

Upd: if I interpret your comment correctly, you're looking for something like this:

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)]
})

Result:

{"penicillin":[3,850],"streptomycin":[0.1,5],"neomycin":[0.09,2]}

This should do the trick.

http://jsfiddle.net/vgW4v/

Array.prototype.max = function() {
    return Math.max.apply(null, this);
};

Array.prototype.min = function() {
    return Math.min.apply(null, this);
};

And arrays are populated with values if they exist and simply calculated.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM