Javascript: Array not pushed right or overwritten after iteration -


i'm working on statistics view via angular-chart shoppinglist-app. should show graph of spended costs every user year. how generate json chart:

$scope.data = {         series: users,         data: []     };     console.log(chartdata);     $scope.load = function(){         for(var = 0; i< months.length; i++){              for(var z = 0; z < chartdata.length; z++){                 var obj = chartdata[z];                 if(obj.year == $scope.dt.getfullyear()){                     if(obj.month == months[i]){                          for(var t =0; t < users.length;t++){                             if(obj.name == users[t]){                                 usercosts[t] = (usercosts[t] + obj.price);                                 console.log(obj.price);                                 console.log(usercosts);                             }                         }                     }                 }             }             console.log(usercosts);             $scope.data.data.push({x:months[i],y: usercosts});             for(var p = 0; p < users.length; p++){                 usercosts[p]=0;             }         }         console.log($scope.data.data);     }; 

the output in console looks this:

[0, 0] 44 [44, 0] [44, 0] [0, 0] [0, 0] 7 [7, 0] [7, 0] 20 [20, 0] [20, 0] 5 [5, 0] [5, 0] [0, 0] [0, 0] [0, 0] [0, 0] [0, 0] 

the array filled fine push statement :

$scope.data.data.push({x:months[i],y: usercosts}); 

just dont work right. "usercosts" in every line same value.... last one; in case 0. although push before go through next month. dont anymore , appreciate smart answers you. best wishes christoph

need understand when push usercosts array chartdata array not copy of usercosts reference array.

then later when set:

 for(var p = 0; p < users.length; p++){       usercosts[p]=0;   }  

you working same array reference got pushed other array.

changes reflected anywhere have reference.


very simple example:

var = [1]; var b = a; // looks simple copy  alert( b[0] ); // alerts 1 // change value of b[0] b[0] = 100; alert( a[0]); // alerts 100 because , b references same array 

Comments