-4

I have an array like the following, that I will fetch from MongoDB:

[
  {date: '2019-10-05', score: 3},
  {date: '2019-10-05', score: 5},
  {date: '2019-10-06', score: 4},
  {date: '2019-10-06', score: 1},
]

I need to make a new array to look like the following:

[
  {date: '2019-10-05', score: [3,5]},
  {date: '2019-10-06', score: [4,1]}
]

Basically grouping the scores into the same arrays based on the date attribute. Any kinds of advice to achieve this is appreciated.

alexW
  • 183
  • 3
  • 13

1 Answers1

1

You can use .reduce() and Object.values() to get the desired output:

const data = [
  {date: '2019-10-05', score: 3}, {date: '2019-10-05', score: 5},
  {date: '2019-10-06', score: 4}, {date: '2019-10-06', score: 1},
];

const result = Object.values(
  data.reduce((r, c) => {
    r[c.date] = r[c.date] || {...c, score: []};
    r[c.date].score.push(c.score);
    return r;
  }, {})
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95