簡體   English   中英

在angular / javascript中添加二維數組

[英]Adding two-dimensional arrays in angular/javascript

我在這里學習基本的javascript,請幫助添加二維數組,其中第0個索引將始終是日期,第1個索引將始終是數組中的整數,我要實現的目標是生成具有唯一對象類型的新數組= A和type = 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],
      ]
  }];

柱塞link

任何幫助深表感謝。

首先,您要遍歷mainArray並將A類型與B類型分開:

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添加到數組中。

(我沒有檢查該代碼是否可以編譯)

我看到您更新了代碼段,因此這是使用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;
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM