Sum the value of a property from obejcts that are matching in another property, from an array of objects

Viewed 28

I have an array of objects, and I'm trying to sum the value of the amount property from each object in the array, based on their address property

I would like to convert something like this:

[
  {
    amount: 10,
    address: a01,
    ...other props...
  },
  {
    amount: 20,
    address: b02,
    ...other props...
  },
  {
    amount: 5,
    address: a01,
    ...other props...
  },
  ...
]

to:

[
  {
    address: a01,
    totalAmount: 15,
    ...other props...
  },
  {
    address: b02,
    totalAmount: someTotaledAmount,
    ...other props...
  },
  ...
]

Should I be using reduce to consolidate the objects in the array?

Thank you!

1 Answers

You could definitely use Array.reduce() to sum the amounts by address. We'd create an object with an entry for each value of address.

We can then use Object.values() to get the result as an array.

let input = [ { amount: 10, address: 'a01', otherValue: 'x' }, { amount: 20, address: 'b02', otherValue: 'y' }, { amount: 5, address: 'a01', otherValue: 'z' } ]

const result = Object.values(input.reduce((acc, { amount, address, ...rest }) => { 
    acc[address] = acc[address] || { address, ...rest, totalAmount: 0 };
    acc[address].totalAmount += amount;
    return acc;
} , {}));

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

You could also use a for ... of loop to do the same thing:

let input = [ { amount: 10, address: 'a01', otherValue: 'x' }, { amount: 20, address: 'b02', otherValue: 'y' }, { amount: 5, address: 'a01', otherValue: 'z' } ]

let result = {};
for(let { amount, address, ...rest} of input) {
    if (!result[address]) {
       result[address] = { address, ...rest, totalAmount: 0 };
    }
    result[address].totalAmount += amount;
}
result = Object.values(result);
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

Related