在angular / javascript中添加二维数组

时间:2017-06-30 16:01:51

标签: javascript angularjs

我正在学习基本的javascript,请帮助,继续添加二维数组,其中第0个索引将始终为日期,第1个索引将始终为数组中的整数,我想要实现的是生成一个新的数组通过添加其第一个二维数组索引,唯一对象类型= A和类型= B.请参阅下面的示例代码

 $scope.mainArray = [{
    type: 'A',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'B',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'A',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'B',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, ];

Should convert to

  $scope.newArray = [{
    type:'A',
    values:[
      [11111,24],
      [11111,24],
      [11111,22],
      [11111,4],
      ]
  },{
    type:'B',
    values:[
      [11111,24],
      [11111,24],
      [11111,22],
      [11111,4],
      ]
  }];

Plunker link

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

首先,你要遍历你的mainArray并从B类中分离出类型A:

var typeAArray = [];
var typeBArray = [];
for(i = 0; i < mainArray.length; i++){
    if(mainArray[i]["type"] = 'A'){
        typeAArray.push(mainArray[i]);
    } else{
        typeBArray.push(mainArray[i]);
    }
}

然后你需要添加所有相应的A类整数。如果2d数组中总是有4个值,则将while循环更改为for(i = 0; i < 4; i++)

var stillValues = true;
//number of values in 2d array
var valueCount = 0;
//new A object
var A = {};
while(stillValues){ 
    for(i = 0; i < typeAArray.length; i++){
        //check if the current A type has the right amount of values
        if(typeAArray.length <= valueCount){
            A["values"][valueCount][0] = typeAArray[i]["values"][valueCount][0];
            A["values"][valueCount][1] += typeAArray[i]["values"][valueCount][1];
            stillValues = true;
        } else{
            stillValues = false;
        }
    }
    valueCount++;
}

请注意,此代码设置了最后一个日期值的日期,因为您没有指定如何确定0索引

对B执行相同操作,然后将A和B添加到数组中。

(我没有检查此代码编译)

答案 1 :(得分:0)

我看到你更新了代码片段,所以这里是一个使用map / filter / reduce来获取你正在寻找的输出的例子。

  $scope.typeAArray = $scope.mainArray.filter(function (obj) {
    return obj.type === 'A';
  }).reduce(function (a, b) {
    var newObj = {
      type: a.type,
      values: []
    };
    a.values.map(function (v, index) {
      newObj.values.push(v);
      newObj.values[index][1] += b.values[index][1];
    });
    return newObj;
  });