Combine one array's values based on duplicate dates

I am trying to solve this and keep getting stuck. I am currently trying to do this with lodash but open to any solution:

EDIT: I’ve done many searches and the suggested links are not the desired output

Array structure:

[
    { "date": "2022-03-01", "A": 11549 },
    { "date": "2022-03-01", "B": 4536 }
]

to become

[
    { "date": "2022-03-01", "A": 11549, "B": 4536 },
]

>Solution :

Would this work for you ?

const arr = [
  { date: '2022-03-01', A: 11549 },
  { date: '2022-03-01', B: 4536 },
  { date: '2022-03-01', C: 8000 },
  { date: '2022-03-01', D: 4000, F: 7500 },
  { date: '2022-04-02', A: 4536 },
];

const r = Object.values(arr.reduce((o, curr) => {
  if (o[curr.date]) {
    for (const entry of Object.entries(curr)) o[curr.date][entry[0]] = entry[1];
  } else o[curr.date] = curr;
  return o;
}, {}))

console.log(r);

Leave a Reply