javascript sum多维数组 [英] javascript sum multidimensional array

查看:56
本文介绍了javascript sum多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个多维数组,我需要合并相等的字段并将总和求和

I have this multidimensional array and I need to merge the fields that are equal and sum the sum values

var data = [
      [
        {field: 123, sum: 100},
        {field: 345, sum: 98}
      ],[
        {field: 123, sum: 12},
        {field: 345, sum: 20}
      ]
    ];

所以从这个数组中,我需要一个像这样的新数组.

So from this array I need a new one like this.

var newArray = [
   {field: 123, sum: 112},
   {field: 345, sum: 118}
];

这是我的代码.

var newArray = [];
for(var i = 0; i < data.length; i++) {
  for(var j = 0; j < data[i].length; j++) {
    var matched = false;
    for(var c = 0; c < newArray.length; c++) {
      if(data[i][j].field == newArray[c].field) {
        matched = true;
        newArray[c].sum + data[i][j].sum;
      }
    }
    console.log(data[i][j]);
    if(!matched) {
      newArray.push(data[i][j]);
    }
  }
}

但是我没有正确的值.console.log(newArray);

but I don't get the values right. console.log(newArray);

推荐答案

您的问题所在

newArray[c].sum + data[i][j].sum;

此行执行计算,但未存储在newArray中.如果将运算符更改为+ =,则您的功能将正常运行.

This line performs the calculation, but it is not stored in newArray. If you change the operator to += your function will work correctly.

newArray[c].sum + data[i][j].sum; // Sums the two values
newArray[c].sum += data[i][j].sum; // Sums and saves them to newArray[c].sum

正确的解决方案在此jsFiddle 中显示.

A correct solution is shown here in this jsFiddle.

var newArray = [];
for(var i = 0; i < data.length; i++){
    var objects = data[i];
    for(var n = 0; n < objects.length; n++){
        var existed = false;
        for(var z = 0; z < newArray.length; z++){
            if(newArray[z].field === objects[n].field){
                newArray[z].sum += objects[n].sum;
                existed = true;
            }
        }
        if(!existed){
            newArray.push({field : objects[n].field, sum: objects[n].sum});                
        }
    }
}

您循环浏览所有元素,然后将它们加到一个名为 newArray 的新数组中.它检查具有该字段的对象是否已经存在,如果存在,则将总和添加到现有元素中.如果没有,它将使用字段值和初始和创建一个新元素.

You cycle through all the elements, and then sum them in a new array called newArray. It looks if an object with the field already exists, and if it does, adds the sum to the existing element. If not, it creates a new element with the field value and the initial sum.

这篇关于javascript sum多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆