Kate
Kate

Reputation: 15

How to get array of objects with unique values?

How to sum object array with the same key value?

I have this array:

let arrData = [{ category: "Main Expenses", amount: 420 },
    { category: "Food", amount: 50 },
    { category: "Main Expenses", amount: 4530},
    { category: "Food", amount: 4520 },
    { category: "Main Expenses", amount: 4530 },
    { category: "Food", amount: 450 },
    { category: "Self Care", amount: 7540 },
    { category: "Child Care", amount: 4570 }]

And I need to get array with unique categories, like this:

[Main Expenses: 9480,
Food: 5020,
Self Care: 7540,
Child Care: 4570]

Upvotes: 1

Views: 85

Answers (1)

brk
brk

Reputation: 50346

The expected output is in array is not possible since array will not support key & value pair. You may opt for object.

You can use reduce and check if the object contains the key by category name. If so then add the amount otherwise create key by the category name and set its value to the amount

let arrData = [{
    category: "Main Expenses",
    amount: 420
  },
  {
    category: "Food",
    amount: 50
  },
  {
    category: "Main Expenses",
    amount: 4530
  },
  {
    category: "Food",
    amount: 4520
  },
  {
    category: "Main Expenses",
    amount: 4530
  },
  {
    category: "Food",
    amount: 450
  },
  {
    category: "Self Care",
    amount: 7540
  },
  {
    category: "Child Care",
    amount: 4570
  }
]

let newData = arrData.reduce((acc, item) => {
  acc[item.category] = acc[item.category] ?
    acc[item.category] + item.amount :
    item.amount;
  return acc;
}, {});

console.log(newData)

Upvotes: 3

Related Questions