Javascript Array按键获取最大值

时间:2014-12-18 12:51:37

标签: javascript arrays sorting

var myarr = new Array();
myarr[0] = {key: 'A', value:900};
myarr[1] = {key: 'B', value:190};
myarr[2] = {key: 'B', value:160};
myarr[3] = {key: 'A', value:10};

我期待的是获得'A的最大值和'B的最大值。

4 个答案:

答案 0 :(得分:1)

单向;

var maxes = {};
for (var i = 0; i < myarr.length; i++)
{
    var item = maxes[myarr[i].key];
    maxes[myarr[i].key] = isNaN(item) ? myarr[i].value : Math.max(item, myarr[i].value);
}

for (var key in maxes)
    alert(key + " max = " + maxes[key]);

答案 1 :(得分:1)

var maxNumbers = {};
var myarr = [
    {key: 'A', value:110},
    {key: 'B', value:190},
    {key: 'B', value:160},
    {key: 'B', value:890},
    {key: 'A', value:80}   
];

for(var i = 0; i < myarr.length; i++) {
    maxNumbers[myarr[i].key] = maxNumbers[myarr[i].key] || myarr[i].value;
    if (maxNumbers[myarr[i].key] < myarr[i].value) {
        maxNumbers[myarr[i].key] = myarr[i].value
    }
}
console.log(maxNumbers) //{ A: 110, B: 890 }

答案 2 :(得分:0)

可能有一些框架,比如使用解决方案的下划线,我只需在数组上循环一次

var max = {}
  , current, i
for(i = 0; i < myarr.length;i++) {
  current = myarr[i];
  // initial value
  if(max[current.key] === undefined) {
    max[current.key] = current.value
  }
  // check if value is higher
  if(current.value > max[current.key]) {
    max[current.key] = current.value;
  }
}
console.log(max)

我还没有测试过它,但它应该给你一个想法

答案 3 :(得分:0)

使用Array.reduce(请参阅MDN

&#13;
&#13;
var myarr = [{key: 'A', value:900},
             {key: 'B', value:190},
             {key: 'B', value:160},
             {key: 'A', value:10}
            ];
var max = myarr.reduce( function(a, b) { return b.value > a ? b : a; });

document.querySelector('#result').textContent = 
     'object with max value in myarr =>; ' + 
      JSON.stringify(max) + ' (value: ' + max.value + ')';
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;