0

I'm trying to walk through a sorted array and count the duplicates to create a new summary-array.

        for (var i = 0; i < newCart.length; i++) {
        //if new item.
        console.log(JSON.stringify(newCart[i - 1]))
        if ( JSON.stringify(newCart[i - 1]) !==  JSON.stringify(newCart[i])) {
            //add to new displayed items in cart
            results.push(newCart[i]);
            results[results.length - 1].count = 1
        }else{
            console.log('second')
            //add one to the count.
            results[results.length - 1].count++;
        }
    }

When I'm looping through this with three items, I get the following output:

undefined
{"id":1,"name":"Skateboard","price":1299,"currency":"SEK","image":"/static/img/products/1.jpg","thumbnail":"/static/img/products/1-t.jpg","description":"This board is the boss!","count":1} main.js:47
{"id":1,"name":"Skateboard","price":1299,"currency":"SEK","image":"/static/img/products/1.jpg","thumbnail":"/static/img/products/1-t.jpg","description":"This board is the boss!","count":1} 

How is it possible that the count variable ends up in the newCart-array?

Himmators
  • 14,278
  • 36
  • 132
  • 223

1 Answers1

1

Because when you do results.push(newCart[i]) it actually puts your cart object into the array, and then you access that newCart[i] object and add count to that newCart[i] object with results[results.length-1].count=1;

Himmators
  • 14,278
  • 36
  • 132
  • 223
Rickard Staaf
  • 2,650
  • 2
  • 14
  • 14
  • Can I make it not put the cart object in, but rather create a copy of it? – Himmators Sep 08 '14 at 09:53
  • http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Rickard Staaf Sep 08 '14 at 10:06
  • Could not let this go, since I know I have done similar things in the past. In the question linked above they are actually trying to clone an object without the values. To do what you want to do a simple: `results.push(Object.create(newCart[i]))` – Rickard Staaf Sep 08 '14 at 10:51
  • It only works in IE9 and newer though (and Chrome, and FF and Safari of course). But it is possible to implement for all brosers, see here for that if neccessary (http://javascript.crockford.com/prototypal.html) – Rickard Staaf Sep 08 '14 at 10:58