Search code examples
javascriptlodash

How to sum up object values in array by some key?


I cannot find solution to this problem.

I have array:

const taxItems = [{
    taxCode: '430',
    taxAmount: 2,
    ItemTaxPercentage: 20,
    taxCategory: '2'
  },
  {
    taxCode: '430',
    taxAmount: 4,
    ItemTaxPercentage: 20,
    taxCategory: '2'
  },
  {
    taxCode: '431',
    taxAmount: 5,
    ItemTaxPercentage: 20,
    taxCategory: '2'
  },
  {
    taxCode: '430',
    taxAmount: 6,
    ItemTaxPercentage: 20,
    taxCategory: '2'
  }
]

And from this array I want to sum up all objects by taxCode.I want to have results like this:

var results = [{
    taxCode: '430',
    taxAmount: 12,
    ItemTaxPercentage: 20,
    taxCategory: '2'
  },
  {
    taxCode: '431',
    taxAmount: 5,
    ItemTaxPercentage: 20,
    taxCategory: '2'
  }
]

I tried to use lodash:

var results =
lodash(taxItems)
  .groupBy('taxCode')
  .map((objs, key) => ({
      'taxCode': key,
      'taxAmount': lodash.sumBy(objs, 'taxAmount') }))
  .value();

But it only works with key value pair. I will loose the original structure of the object.

What would be the correct solution to my problem?


Solution

  • Spread the 1st object of each group into the result object, to get the recurring properties:

    const taxItems = [{"taxCode":"430","taxAmount":2,"ItemTaxPercentage":20,"taxCategory":"2"},{"taxCode":"430","taxAmount":4,"ItemTaxPercentage":20,"taxCategory":"2"},{"taxCode":"431","taxAmount":5,"ItemTaxPercentage":20,"taxCategory":"2"},{"taxCode":"430","taxAmount":6,"ItemTaxPercentage":20,"taxCategory":"2"}];
    
    const results = _(taxItems)
      .groupBy('taxCode')
      .map((objs, taxCode) => ({
          ..._.head(objs),
          taxCode,
          taxAmount: _.sumBy(objs, 'taxAmount') }))
      .value();
      
    console.log(results);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>