Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge object data with same date

I have the following array I need help with.

let test = [
{
  date: ["2021-11-09", "2021-11-09", "2021-11-10", "2021-11-10"],
  amount: [0.5, 0.5, 1, 2],
}];

How can I merge the amounts that have the same date? I want the data to be returned as below:

date: ["2021-11-09", "2021-11-10"],
amount: [1, 3],

Thank you in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As mentioned in the comments, this is just a ‘group by’ by date from the date array, summing the elements at the same index in the amount array.

let test = [
  {
    date: ['2021-11-09', '2021-11-09', '2021-11-10', '2021-11-10'],
    amount: [0.5, 0.5, 1, 2],
  },
];

const result = test.map(({ date, amount }) => {
  const grouped = date.reduce((a, d, i) => a.set(d, (a.get(d) ?? 0) + amount[i]), new Map());

  return {
    date: [...grouped.keys()],
    amount: [...grouped.values()],
  };
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading