对多维数组中的数值求和

时间:2015-08-07 07:21:25

标签: javascript jquery json

我在Javascript中有这样的数组:

var scores = [
    {"firstName":"John", "value": 89},
    {"firstName":"Peter", "value": 151},
    {"firstName":"Anna", "value": 200},
    {"firstName":"Peter", "value": 22},
    {"firstName":"Anna","value": 60}
];

我想转换这个数组,以便组合相似名字的值。我期望的结果是:

var scores = [
    {"firstName":"John", "value": 89},
    {"firstName":"Peter", "value": 173},
    {"firstName":"Anna", "value": 260}
];

此致

3 个答案:

答案 0 :(得分:0)

只需:



var scores = [{
  "firstName": "John",
  "value": 89
}, {
  "firstName": "Peter",
  "value": 151
}, {
  "firstName": "Anna",
  "value": 200
}, {
  "firstName": "Peter",
  "value": 22
}, {
  "firstName": "Anna",
  "value": 60
}];

var names = {};
var new_arr = [];

scores.forEach(function(entry) {
  if (names.hasOwnProperty(entry.firstName)) {
    new_arr[names[entry.firstName]].value += entry.value;
  } else {
    names[entry.firstName] = new_arr.length;
    new_arr.push({
      "firstName": entry.firstName,
      "value": entry.value
    });
  }
});

console.log(new_arr);




答案 1 :(得分:0)

Why the validation for file picker is not working here.

答案 2 :(得分:0)

这是一个两步解决方案。首先计算所有项目。第二,将结果格式化为所需的样式。

var scores = [
    { "firstName": "John", "value": 89 },
    { "firstName": "Peter", "value": 151 },
    { "firstName": "Anna", "value": 200 },
    { "firstName": "Peter", "value": 22 },
    { "firstName": "Anna", "value": 60 }
];
var result = [],
    r0 = scores.reduce(function (r, a) {
        r[a.firstName] = (r[a.firstName] || 0) + a.value;
        return r;
    }, {}), // { "John": 89, "Peter": 173, "Anna": 260 }
    i;
for (i in r0) {
    result.push({ firstName: i, value: r0[i] });
}
document.getElementById('out').innerHTML = JSON.stringify(result, null, 4);
<pre id="out"></pre>