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?

asked Sep 8, 2014 at 9:39
9
  • You cannot do resulst[].count .... Commented Sep 8, 2014 at 9:41
  • why can't I do that? Commented Sep 8, 2014 at 9:42
  • is that correct way for adding property in array property?? We cannot add property to property of array... Commented Sep 8, 2014 at 9:43
  • 1
    There is no count property in javascript I am guessing you need the .length Commented Sep 8, 2014 at 9:45
  • 1
    are you trying to reset your counter value? Commented Sep 8, 2014 at 9:48

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Can I make it not put the cart object in, but rather create a copy of it?
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]))
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)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.