Mischa
Mischa

Reputation: 2139

javascript .push overwrites previous array values by duplicating the new values

(this is in Angular) I need to make an array of arrays to be displayed in a chart. The values are generated by this code:

$scope.getData = function() {
  $scope.series.length = 0
  $scope.allData.length = 0
  var dataArray = [];
  var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"]

  for (var i = 0 ; i < $scope.dataDisplayModel.length ; i++) {
    if ($scope.dataDisplayModel[i].checked === true) {
      var field = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field)
      dataArray.length = 0;

      for (var j = 0 ; j < 5 ; j++) {
        var arrayList = $filter('filter')($scope.dataList.values, dateArray[j], true);
        var sum = _.sum(arrayList, field);
        dataArray.push(sum);
      }
      $scope.allData.push(dataArray);
    }
  }
}

with:

$scope.allData = the target array
dataDisplayModel = an array of objects containing field names and a checked proporty
$scope.dataList = json array containing the original data

For some reason every time i push to $scope.allData it overwrites the previous arrays leaving me with duplicates. So if i check 2 fields i get

$scope.allData = [[ARRAY2],[ARRAY2]]

and if i check 3 fields i get

$scope.allData = [[ARRAY3],[ARRAY3],[ARRAY3]]

etc. I can't figure out why it keeps overriding my previous arrays.

Upvotes: 2

Views: 5027

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29836

Simply create a new local array before pushing the same one (the same reference) each time:

    $scope.getData = function() {
      $scope.series.length = 0
      $scope.allData.length = 0

      var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"]

      for (var i = 0 ; i < $scope.dataDisplayModel.length ; i++) {
        var dataArray = []; // create a new local var each iteration
        if ($scope.dataDisplayModel[i].checked === true) {
          var field = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field);


          // dataArray.length = 0; // this will not clear the array!!!!

          for (var j = 0 ; j < 5 ; j++) {
            var arrayList = $filter('filter')($scope.dataList.values, dateArray[j], true);
            var sum = _.sum(arrayList, field);
            dataArray.push(sum);
          }
          $scope.allData.push(dataArray);
        }
      }
    }

Upvotes: 3

Related Questions