How to get the sum of a key in an array of object and remove duplicates of consecutive objects?

Viewed 1126

I have a main array -

const arr = [
    {  description: 'Senior', amount: 50 },
    {  description: 'Senior', amount: 50 },
    {  description: 'Adult', amount: 75 },
    {  description: 'Adult', amount: 35 },
    {  description: 'Infant', amount: 25 },
    {  description: 'Senior', amount: 150 }
]

I want help with an es6 operation which will add the amount based on the key(description) and remove the duplicates.

Result array will somewhat look like -

const newArr = [
        {  description: 'Senior', amount: 120 },
        {  description: 'Adult', amount: 110 },
        {  description: 'Infant', amount: 25 },
        {  description: 'Senior', amount: 150 }
]

I have been using the reduce operator to achieve this using the solutions from below, but that removes the non-consecutive objects as well.

It would be really helpful if someone can help me with some es6 operators to perform the same operation.

3 Answers

const arr = [
  { description: "Senior", amount: 50 },
  { description: "Senior", amount: 50 },
  { description: "Adult", amount: 75 },
  { description: "Adult", amount: 35 },
  { description: "Infant", amount: 25 },
];

const result = Object.values(
  arr.reduce((acc, item) => {
    acc[item.description] = acc[item.description]
      ? { ...item, amount: item.amount + acc[item.description].amount }
      : item;
    return acc;
  }, {})
);

console.log(result);

  • Using Array#reduce, iterate over the array while updating a Map where the key is the description and the value is the record with total amount
  • Using Map#values, get the list of grouped objects

const arr = [ { description: 'Senior', amount: 50 }, { description: 'Senior', amount: 50 }, { description: 'Adult', amount: 75 }, { description: 'Adult', amount: 35 }, { description: 'Infant', amount: 25 } ];

const res = [...
  arr.reduce((map, current) => {
    const { description } = current;
    const grouped = map.get(description);
    if(!grouped) {
      map.set(description, { ...current });
    } else {
      map.set(description, { ...grouped, amount: grouped.amount + current.amount })
    }
    return map;
  }, new Map)
  .values()
];

console.log(res);

You may just use this snippet

array.filter((item, index) => array.indexOf(item) === index);

Refer to this link for more details. Or just copy this solution.

Related