Trying to count a few objects in an array of objects so that it checks 2 properties and if they are the same, it increases the count.
Edit: basically, I want to check the itemId and the orderId and if there is another object with the same values in the array, I want to increase the count
input =>
[{itemName: "Burger", itemId: 111, orderId: 123},
{itemName: "Burger", itemId: 111, orderId: 123},
{itemName: "Pizza", itemId: 222, orderId: 456}]
output =>
[{itemName: "Burger", itemId: 111, orderId: 123, count: 2},
{itemName: "Pizza", itemId: 222, orderId: 456, count: 1}]
I tried to use a reduce function and a simple forEach but the closest I got was:
counter = {}
myArray.forEach(function(obj) {
var key = JSON.stringify(obj)
counter[key] = (counter[key] || 0) + 1
})
result =>
[{itemName: "Burger", itemId: 111, orderId: 123}: 2,
{itemName: "Pizza", itemId: 222, orderId: 456}: 1 ]
Can I get some help with this please?