如何使用Array.reduce()?

时间:2018-05-24 11:20:32

标签: javascript arrays

我有一个JSON响应,如下所示:

[
{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}],
]

如何对每个数据元素中的每个“值”求和(按列方式)并得到如下结果:

[{"name": "something", "data":[{"value":50,"id":1},{"value":100,"id":2}]

如何使用array.reduce()或者是否有其他方法来实现上述结果?

5 个答案:

答案 0 :(得分:2)

尝试以下逻辑。

var series = [{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]}, ... , ....]

var resultSeries = series.reduce((acc, cur) => {
    var result = {
        name: ‘Something’,
        data: []
    };
    var dataArray = acc.data.map((el, i) => {
        var curData = cur.data[i] || {};
        var sum = (el.value || 0) + (curData.value || 0);
        return {
            value: sum
        }
    });
    result.data = dataArray ;
    return result;
})

现在resultSeries将会举行

[{"name": "something", "data":[{"value":50,"id":1},{"value":100,"id":2}]

答案 1 :(得分:1)

您可以将对象作为id的哈希表,并对值进行求和。

var array = [{ name: "a", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "b", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "c", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "d", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "e", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }],
    result = { name: 'something', data: Object.values(array.reduce((r, { data }) => {
        data.forEach(({ value, id }) => {
            r[id] = r[id] || { value: 0, id };
            r[id].value += value;
        });
        return r;
    }, Object.create(null))) };

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

试试此代码

<script>
 var numbers = [
{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
];

function getSum(total, val) {
  total.data[0].value = total.data[0].value + val.data[0].value;
  total.data[1].value = total.data[1].value + val.data[1].value;
  return total;
 }
function myFunction(item) {
   document.getElementById("demo").innerHTML = 
  JSON.stringify(numbers.reduce(getSum));
}

打印

Sum of numbers in array: {"name":"a","data":[{"value":50,"id":1},{"value":100,"id":2}]}

代码只是在每次迭代时添加值并更新现有值。

答案 3 :(得分:0)

使用Array.reduceArray.map

&#13;
&#13;
var arr =[{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}]}];

var result = {
   "name" : "something",
   "data" : arr.reduce((a,c) => { // reduces/merges 2 records of arr
      a.data.map((v, i) => { // add values for the 2 records (column wise)
        v.value = v.value + c.data[i].value;
        return v;
      });
      return a;
   })
};
console.log(result);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

我相信您的JSON数据看起来就像我在下面的代码段中使用的那样。你可以这样做:

&#13;
&#13;
    a = [
    {"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    ]
    
    let reducer = (accumulator, currValue) => {
            accumulator.name = "something";
        	for (let i = 0; i < accumulator.data.length; i++) {
        			accumulator.data[i].value += currValue.data[i].value;
            }
            return accumulator
        };

    // This will give the result you want:

    console.log(a.reduce(reducer));
&#13;
&#13;
&#13;

结果将是:

{"name":"something","data":[{"value":50,"id":1},{"value":100,"id":2}]}