2

So im trying to fill in the array "cat" with five rows that will keep a running count of the number of times each category occurs in a step. The problem is the loop executes but it doesn't output the results one by one so I can see the progression (time series) how each category's count goes up. All it does it spit out the total count for each category

            this.cat = [];
            this.cat[0] = 0;
            this.cat[1] = 0;
            this.cat[2] = 0;
            this.cat[3] = 0;
            this.cat[4] = 0;
            this.total = 0;
        },
        model: vote,
        parse: function(data)
        {
            data = data.response ? data.response : data;

            if(data.length == 0)
                return;

            for (var i = 0; i < data.length; i++) {
                this.itemParse(data[i]);
            };

            return data;
        },
        itemParse: function(item){
            this.cat[item.user_vote_index]++;
            this.total++;
            console.log(this.cat);
            item.cat = this.cat;
            item.total = this.total;
            console.log(item);
            return item;
        }
    })
})`

Here is my console log from when i do console.log(this.cat);console.log(this.cat); [1, 0, 0, 0, 0] stats.js:33

[1, 0, 0, 1, 0] stats.js:33

[1, 0, 1, 1, 0] stats.js:33

etc until

[8, 6, 1, 2, 1]

which is how i want the data to be stored (one iteration at a time); However when I console log the collection item.cat gives me [8, 6, 1, 2, 1] for every row

Steeve17
  • 492
  • 6
  • 19

1 Answers1

1

You have to modify your itemParse function:

itemParse: function(item){
  this.cat[item.user_vote_index]++;
  this.total++;
  // here you have to clone the array instead of creating a reference to it
  item.cat = _.clone(this.cat);
  item.total = this.total;
  return item;
}
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55