`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:
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);