0

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?

1 Answer 1

1

You can use a combination of Object.values and Array.prototype.reduce:

var input = [{itemName: "Burger", itemId: 111, orderId: 123},
 {itemName: "Burger", itemId: 111, orderId: 123},
 {itemName: "Pizza",  itemId: 222, orderId: 456}];
 
 var result = Object.values(input.reduce( (acc, i) => {
  var key = JSON.stringify(i)
  return {
    ...acc,
    [key]: {...i, count: (acc[key]?.count || 0) + 1}
  }
 },{}));
 
 console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.