I have to remove all the objects from array that contain the same id present in another array.
This code works
myArray = [{id: 1, value: 'a'}, {id: 2, value: 'b'}, {id: 3, value: 'c'}];
itemsToRemove = [{id: 2, value: 'x'}, {id: 3, value: 'y'}];
for (const item of itemsToRemove) {
myArray.splice(myArray.findIndex(a => a.id === item.id), 1);
}
but I'm looking for a more elegant way to do it. I've tried also
const newArray = myArray.filter(a => itemsToRemove.findIndex(i => i.id === a.id));
but doesn't works. (it creates a new array, but at least one item with the same id remains in the new array).
Is there a clean and concise way to do it?
CodePudding user response:
Test | Result | Operations/second |
---|---|---|
findIndex | 10.63% slower | 26632285 |
find | 12.39% slower | 26107649 |
some | fastest | 29799972 |