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

compare two array of object

I have an array of objects in JavaScript and would like to filter it, if there is two events that are equel so their days concat and if there is duplicate value in days array remove it.

here is my array:

[ { event: 'approvalDate', days: [ 1, 2, 3, 4, 5] },
  { event: 'appointDate', days: [ 1 ] },
  { event: 'approvalDate', days: [ 120, 14, 9, 4, 1, 2 ] } ]

I want the result like this

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

[ { event: 'approvalDate', days: [ 1, 2, 3, 4, 5,120, 14, 9] },
  { event: 'appointDate', days: [ 1 ] },
 ]

>Solution :

const items = [
  { event: 'approvalDate', days: [1, 2, 3, 4, 5] },
  { event: 'appointDate', days: [1] },
  { event: 'approvalDate', days: [120, 14, 9, 4, 1, 2] },
];

const result = [];

items.forEach((item) => {
  if (!result.find((e) => e.event === item.event)) {
    result.push(item);
  } else {
    const index = result.findIndex((e) => e.event === item.event);
    result[index].days = [...new Set([...result[index].days, ...item.days])];
  }
});
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