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?
asked Sep 8, 2014 at 9:39
Himmators
15.1k40 gold badges137 silver badges235 bronze badges
1 Answer 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
15.1k40 gold badges137 silver badges235 bronze badges
answered Sep 8, 2014 at 9:47
Rickard Staaf
2,8702 gold badges17 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Himmators
Can I make it not put the cart object in, but rather create a copy of it?
Rickard Staaf
Rickard Staaf
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
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 (javascript.crockford.com/prototypal.html)
lang-js
countproperty in javascript I am guessing you need the.length