I have two arrays of objects and I need to intersect between the arrays to find out the common one and delete it from the first array which does not have the same item based on one of the keys.
Note that I want to mutate the first array itself.
Here is my code sample and what I tried with .map but did not get the expected result.
(() => {
const first = Array.from({ length: 5 }, (_, i) => ({
id: `in-${i}`,
name: "one",
age: `${i * 5}`
}));
const second = Array.from({ length: 3 }, (_, i) => ({
id: `in-${i}`,
name: "two"
}));
console.log({ first });
console.log({ second });
const sid = second.map(s => s.id);
first.map((f, i) => {
if (sid.includes(f.id)) {
console.log("✔️ included");
} else {
console.log("👎🏻 not included");
first.splice(i, 1);
}
});
console.log("...now...");
console.log({ first });
console.log({ second });
})();
This does not delete the last array element of first array.
Expected output:
[ { id: 'in-0', name: 'one', age: '0' },
{ id: 'in-1', name: 'one', age: '5' },
{ id: 'in-2', name: 'one', age: '10' }
] }
Actual output:
[ { id: 'in-0', name: 'one', age: '0' },
{ id: 'in-1', name: 'one', age: '5' },
{ id: 'in-2', name: 'one', age: '10' },
{ id: 'in-4', name: 'one', age: '20' } ] }
What mistake am I doing here? Kindly help.
Also, suggest any other shorter and simplified ways. I think I can use .reduce / forEach here but I do not know how.
.map()call.first = first.map(..)so I have to change the first array itself