从JavaScript字典对象中获取最大值

时间:2013-12-26 11:28:15

标签: javascript arrays max

我有像

这样的JavaScript dict对象
[2,1920][2,1080][2,700][3,1200][3,1000][3,800][4,1000][4,900][4,1920]

我需要一个最大值数组,按键,e。 G:

[2,1920][3,1200][4,1920]

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:3)

简单地循环并计算最大值。既然你只给出了数据结构的伪表示法,我只能给你(pythonic)伪代码:

maxima = new dict()
for each (key, value) in your_object:
    if not( key ispartof maxima ) or maxima.get(key) < value:
        maxima.set(key, value)

答案 1 :(得分:0)

不是最短路(2n复合体),但它有效:

var dataArr = [[2,1920],[2,1080],[2,700],[3,1200],[3,1000],[3,800],[4,1000],[4,900],[4,1920]];
dataArr.sort(function (a,b) {
    if (a[0] === b[0]) {
        return b[1] - a[1];
    }
});
var key = dataArr[0][0];
var currentKey;
var index = 1;
var arrLength = dataArr.length;

for (index; index < arrLength; index++) {
    currentKey = dataArr[index][0];
    if (key === currentKey) {
        delete dataArr[index];
    } else {
        key = currentKey;
    }
}
console.log(dataArr);

答案 2 :(得分:0)

我认为这就是你想要的。

var dict, maxes, keys, keyi, key;

// you can represent your data in a dictionary like this
dict = {2: [1920,1080,700], 3: [1200,1000,800], 4: [1000,900,1920]};

// this will get the max values for each key in the dicionary
maxes = {};
keys = Object.keys(dict);
for (keyi = 0; keyi < keys.length; keyi++) { 
    key = keys[keyi];
    maxes[key] = Math.max.apply(Math, dict[key]); 
}

最后,maxes将包含:

{2: 1920, 3: 1200, 4: 1920}