1

I have an array of objects, which I want to sum by condition.

[{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}]

Is there is a way to map the values, such as I will have two sums, one is 170, of prefix 'a', and one of 150 of prefix 'b'?

4
  • can you explain this a bit more? Commented Nov 2, 2021 at 14:19
  • @Kektuto Assuming I have an array, I'd like to sum it, by the value of each prefix. The sum of all amounts with prefix 'a' are 170, 100+70 , and the sum of all amounts with prefix 'b' are 150, as there are two objects with the prefix 'b', one has amount of 100, and the other has amount of 50 Commented Nov 2, 2021 at 14:21
  • @user3150947 what output do you expect? Commented Nov 2, 2021 at 14:24
  • {'a' : 170, 'b': 150} Commented Nov 2, 2021 at 14:32

2 Answers 2

4

const result = [{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}].reduce(
  (acc, {amount, prefix}) => {
    return {
      ...acc,
      [prefix]: acc[prefix] + amount
    }
   
  }, {a: 0, b: 0}
);


console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

2

function compute_sums(acc, curr) {
    if (acc[curr['prefix']]) {
        acc[curr['prefix']] += curr['amount']
    } else {
       acc[curr['prefix']] = curr['amount']
   }
   return acc;
}
const arr = [{amount:100, prefix:'c'}, {amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}];
const answer = arr.reduce(compute_sums, {});
console.log(answer);

Similar answer to Ali, but mine will compute the sums for any prefix, not just a and b.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.