-4

I have an array like this:

let purchases = [{
    year: 2019,
    sum: 3000
  },
  {
    year: 2019,
    sum: 5500
  },
  {
    year: 2020,
    sum: 2300
  }
]              

I need to calculate the value of the sum for each year, that is, to get the following result.

{"2019": 8500, "2020": 2300}

How can I do that?

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
First Sin
  • 94
  • 6
  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and use the available [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Nov 14 '20 at 09:51

1 Answers1

2

This can be done using Array.prototype.reduce.

let purchases = [{
    year: 2019,
    sum: 3000
  },
  {
    year: 2019,
    sum: 5500
  },
  {
    year: 2020,
    sum: 2300
  }
];

const output = purchases.reduce((acc, cur) => {
  acc[cur.year] ? acc[cur.year] += cur.sum : acc[cur.year] = cur.sum;
  return acc;
}, {});
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
  • That's one of the most asked questions (how to group an array of objects). Close them as dupe instead of adding just another `.reduce()` approach... – Andreas Nov 14 '20 at 09:59