0

I have got array of objects:

[
  {date: 'Mon', count: 5, ids: '3,7'},
  {date: 'Mon', count: 1, ids: '2'},
  {date: 'Thu', count: 4, ids: '16,23'},
  {date: 'Fri', count: 2, ids: '0,1'},
  {date: 'Fri', count: 2, ids: '8,9'},
]

And i want summ count for equal dates and get array of objects again. Expected output:

[
  {date: 'Mon', count: 6},
  {date: 'Thu', count: 4},
  {date: 'Fri', count: 4},
]

Whats the best way to do this?

pwf98232
  • 3
  • 1

2 Answers2

1

You can use Array#reduce with an object as the accumulator.

const arr = [
  {date: 'Mon', count: 5, ids: '3,7'},
  {date: 'Mon', count: 1, ids: '2'},
  {date: 'Thu', count: 4, ids: '16,23'},
  {date: 'Fri', count: 2, ids: '0,1'},
  {date: 'Fri', count: 2, ids: '8,9'},
];
const res = Object.values(arr.reduce((acc, {date, count})=>{
  (acc[date] ??= {date, count: 0}).count += count;
  return acc;
}, {}));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

First reduce your input array to group common dates and aggregate their count.

Then you can map over the object's entries to get the key value pairs as an array.

const input = [
  {date: 'Mon', count: 5, ids: '3,7'},
  {date: 'Mon', count: 1, ids: '2'},
  {date: 'Thu', count: 4, ids: '16,23'},
  {date: 'Fri', count: 2, ids: '0,1'},
  {date: 'Fri', count: 2, ids: '8,9'},
];

const inputByDate = input.reduce((acc, { date, count }) => {
  if (date in acc) {
    acc[date] += count;
  } else {
    acc[date] = count;
  }
  return acc;
}, {});

const result = Object.entries(inputByDate).map(([date, count]) => ({ date, count }));

console.log(result);
Anson Miu
  • 1,171
  • 7
  • 6