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

How to remove duplicate elements in two dimensional array by adding the values

I have a two dimensional array as such

const arr = [[1664164800000,38],[1669006800000,11],[1669611600000,4],[1669611600000,12],[1670216400000,8]]

and I would like to filter the duplicate keys and add the values as such

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

[[1664164800000,38],[1669006800000,11],[1669611600000,16],[1670216400000,8]]

Is it possible to achieve?

>Solution :

You can use reduce for this purpose

arr.reduce((acc, [key, value]) => {
  const dict = acc[1];
  if (!dict[key]) {
    const item = [key, value]; // add new item (copy value to prevent mutation of passed input)
    acc[0].push(item);
    dict[key] = item;
  } else {
    const [_, prevValue] = dict[key];
    dict[key][1] = prevValue + value; // modify/mutate item value
  }
  return acc;
}, [[], {}])[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