-3

I have the following array:

const sales = [
  { name: 'a', count: 0 },
  { name: 'a', count: 0 },
  { name: 'b', count: 0 }
]

I want to count their occurrence:

const result = []
sales.forEach(sale => {
  if (result.includes(sale)) { // check if the item is in the new array
    sale.count += 1 // if it is, add one to count
  } else {
    result.push(sale) // if not, put the item in the array 
  }
})

But the if statement never returns true. Why is this and how to fix it?

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • "[How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)". – Uwe Keim Jan 03 '20 at 06:17
  • You never can have two same objects in that array of object literals, though they might have the same content. – Teemu Jan 03 '20 at 06:20
  • 2
    `{ name: 'a', count: 0 } === {name: 'a', count: 0 }` will return `false`, because although those two objects contain the same properties and values they do not represent the same object in memory, which is what you are testing for (and how I imagine `.includes` works). You probably want to compare the `name` property instead. – Alexander Nied Jan 03 '20 at 06:22
  • is `count` always 0 in sales object? – BlackPearl Jan 03 '20 at 06:32
  • What is the expected output? – adiga Jan 03 '20 at 06:42
  • Does this answer your question? [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – starball Nov 11 '22 at 05:04

1 Answers1

1

There exists a good answer already at https://stackoverflow.com/a/201471/2358409 that explains why your solution doesn't work.

To make it work, you could transform individual objects in the array to string, and use a Set to count distinct elements.

const sales = [
  { name: 'a', count: 0 },
  { name: 'a', count: 0 },
  { name: 'b', count: 0 }
]

const count = new Set(sales.map(s => JSON.stringify(s))).size;
console.log(count)
uminder
  • 23,831
  • 5
  • 37
  • 72
  • It looks like OP wants to store the count of the similar objects in a property of the objects themselves, not just count the occurrences. – Teemu Jan 03 '20 at 06:46
  • In his question he writes "I want to count their occurrence". – uminder Jan 03 '20 at 06:48
  • Yes, but in the code, there's `sale.count += 1`, which indicates where the output should actually occur. – Teemu Jan 03 '20 at 06:49