2

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

2
  • It sounds like you are adding a reference rather than a separate object into the array. You're just changing the value of the reference along the way. Commented May 1, 2015 at 10:25
  • correct, i think i misunderstood the .length Commented May 1, 2015 at 10:27

1 Answer 1

3

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);
        }
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.