Question

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.

$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.

$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)

Was it helpful?

Solution

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];
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top