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 2 arrays of objects and add a property to the object with the matching id

`I have two arrays of objects like as below. I want to compare the ids of the two arrays and return isSomeProperty with boolean value.

const arr1 = [
{ id: 001, name: 'abc' },
{ id: 002, name: 'def' },
{ id: 003, name: 'ghi' },
{ id: 004, name: 'jkl' },
{ id: 005, name: 'mno' }
];

const arr2 = [
{ id: 001, name: 'abc' },
{ id: 002, name: 'def' }
];

arr1.forEach((item1) => {
    arr2.forEach((item2) => {
if (item1.id === item2.id) {
return {
...item1,
isSomeProperty: true;
}
} else {
return {
...item1,
isSomeProperty: false;
}
}
});
});
return arr1;

Is there a way to avoid using two forEach loops and done in an efficient way.

Expected Output:

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

const arr1 = [  
{ id: 001, name: 'abc', isSomeProperty: true },  
{ id: 002, name: 'def', isSomeProperty: true },  
{ id: 003, name: 'ghi', isSomeProperty: false },  
{ id: 004, name: 'jkl', isSomeProperty: false },  
{ id: 005, name: 'mno', isSomeProperty: false } 
];

>Solution :

const arr1 = [
  { id: 001, name: 'abc' },
  { id: 002, name: 'def' },
  { id: 003, name: 'ghi' },
  { id: 004, name: 'jkl' },
  { id: 005, name: 'mno' }
];

const arr2 = [
  { id: 001, name: 'abc' },
  { id: 002, name: 'def' }
];

const result = arr1.map(item1 => {
  const item2 = arr2.find(item2 => item1.id === item2.id);
  return {
    ...item1,
    isSomeProperty: !!item2 // convert item2 to a boolean value
  };
});

console.log(result);
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