2

I'm working on a statistics view via Angular-Chart for a shoppinglist-App. It should show a graph of all spended costs by every user for a year. Now this is how I generate the JSON for the Chart:

$scope.data = {
        series: users,
        data: []
    };
    console.log(chartdata);
    $scope.load = function(){
        for(var i = 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 the console looks like 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 is filled fine but the push statement :

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

just dont work right. "usercosts" is in every line the same value.... the last one; in this case 0. Although I push before I go through the next month. I dont now what to do anymore and would appreciate to get some smart answers from you. best wishes Christoph

Christoph
  • 23
  • 3

1 Answers1

0

Need to understand that when you push the usercosts array into the chartData array it is not a copy of usercosts it is a reference to that array.

Then later when you set:

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

You are working with the same array reference that just got pushed into the other array.

Changes will be reflected anywhere you have a reference.


Very simple example:

var a = [1];
var b = a; // looks like it would be a simple copy 
alert( b[0] ); // alerts 1
// change value of b[0]
b[0] = 100;
alert( a[0]); // alerts 100 also because a and b are references to same array
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Just for completeness sake: http://stackoverflow.com/questions/8660901/do-objects-pushed-into-an-array-in-javascript-deep-or-shallow-copy – JavaScript Jul 16 '15 at 13:45
  • Ok thank you very much :). I will try to find another solution – Christoph Jul 16 '15 at 18:41
  • you can use angular.copy() to make copies. The important part to understand though is how protypical inheritance works in javascript and it is really important to understand when working with angular in particular – charlietfl Jul 16 '15 at 18:47