Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce Multiple Objects into One, Adding Values Together

Let's say I have an array of objects:

[
    {
        category: 'Category A',
        mainUnits: 5,
        subUnits: 3
    },

    {
        category: 'Category A',
        mainUnits: 9,
        subUnits, 12
    },

    {
        category: 'Category B',
        mainUnits: 4,
        subUnits, 6
    },

    {
        category: 'Category B',
        mainUnits: 2,
        subUnits, 4
    }
]

However, I can't seem to get an array that looks like this:

[
    {
        category: 'Category A',
        mainUnits: 14,
        subUnits: 15
    },

    {
        category: 'Category B',
        mainUnits: 6,
        subUnits: 10
    }
]

I have been able to make some sort of headway, but can't quite get the exact result I need. Any guidance is greatly appreciated, thanks!

like image 797
Lushmoney Avatar asked Jun 24 '26 01:06

Lushmoney


1 Answers

The .reduce array method seems like a good fit here.

Use the array .find method to see if there is already an item with that category in the result. If so, add the fields, but if not, add the item to the result:

const input = [{
  category: 'Category A',
  mainUnits: 5,
  subUnits: 3
}, {
  category: 'Category A',
  mainUnits: 9,
  subUnits: 12,
}, {
  category: 'Category B',
  mainUnits: 4,
  subUnits: 6,
}, {
  category: 'Category B',
  mainUnits: 2,
  subUnits: 4,
}];

const result = input.reduce((result, item) => {
  const existing = result.find(x => x.category === item.category);
  if (existing) {
    existing.mainUnits += item.mainUnits;
    existing.subUnits += item.subUnits;
  } else {
    result.push(item);
  }

  return result;
}, []);

console.log(result);
like image 196
CRice Avatar answered Jun 26 '26 15:06

CRice