如何使用javascript或angular将一个数组的每个元素添加到其他数组中的相应元素

时间:2021-11-15 07:10:00

I need to add the elements of arrays together in order, very similar to the question at [How can I add each element of one array to another one's corresponding element using a ParallelStream?, but I'm using javascript and angular. My arrays can come in with any amount of elements up to 31 (days), but they will all always be the same amount of elements across each data object.

我需要按顺序将数组元素添加到一起,非常类似于[如何使用ParallelStream将一个数组的每个元素添加到另一个数据的相应元素?中的问题,但我使用的是javascript和angular。我的数组可以包含任意数量的元素,最多可达31天(天),但它们在每个数据对象中的元素数量始终相同。

$scope.test31days = {
  "change_series": [
    { "data": [0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,0,0],
      "name": "EMERGENCY",
      "color": "#904040"},
    { "data": [0,1,3,0,0,0,0,1,2,3,3,0,0,0,2,1,1,1,0,0,1,1,3,3,1,0,0,1,2,2,0],
      "name": "MINOR",
      "color": "#333"},
    { "data": [0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0],
      "name": "MAJOR",
      "color": "#666"}
  ],
  "change_title": "CHANGES"
}

My console output tells me I'm separating the elements correctly (to some extent), but when I run this with the if/else if statement, I crash the browser, so I know I'm screwing something up.

我的控制台输出告诉我我正确地分离了元素(在某种程度上),但是当我用if / else if语句运行它时,我崩溃浏览器,所以我知道我搞砸了。

$scope.getTotalChanges = function(){
  var series = $scope.test31days.change_series;
  var arry = [];

  for(var i = 0; i < series.length; i++){
    // console.log('change_series loop #', i);
    // console.log('change_series.data length', series[i].data.length);

    var seriesData = series[i].data;
    // console.log('series[i].name', series[i].name)        
    // console.log('seriesData', seriesData)

    for(var j = 0; j < seriesData.length; j++){
      console.log('For inner #', j);
      console.log('seriesData #', seriesData[j]);

      if (j = 0) {
        arry = seriesData;
      } else if (j > 0) {
        arry[j] += seriesData[j]
      };
    }
  }

  // return series;
  console.log('arry ', arry);
  return arry;
};

My end goal is to have a single array of the data for the 31 (days)

我的最终目标是为31(天)提供单个数据数组

1 个解决方案

#1


1  

var series = $scope.test31days.change_series;
var dataLength = series[0].data.length;
var result = Array.apply(null, new Array(dataLength)).map(Number.prototype.valueOf,0); //initialize result array with zeros

for(var i = 0; i < series.length; i++) {
  for(var j = 0; j < dataLength; j++) {
    result[j] += series[i].data[j];
  }
}

#1


1  

var series = $scope.test31days.change_series;
var dataLength = series[0].data.length;
var result = Array.apply(null, new Array(dataLength)).map(Number.prototype.valueOf,0); //initialize result array with zeros

for(var i = 0; i < series.length; i++) {
  for(var j = 0; j < dataLength; j++) {
    result[j] += series[i].data[j];
  }
}