Home > other >  Map an array by value
Map an array by value

Time:11-03

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'?

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

  • Related