Remove object from array based on array of some property of that object
You don't need two nested iterators if you use a built-in lookup function
objList = objList.filter(o => idsToRemove.indexOf(o.id) < 0);
Documentation:
Array.prototype.indexOf()
Array.prototype.includes()
You can use Array.includes
which check if the given string exists in the given array and combine it with an Array.filter
.
const idsToRemove = ['3', '1'];
const objList = [{
id: '1',
name: 'aaa',
},
{
id: '2',
name: 'bbb',
},
{
id: '3',
name: 'ccc',
},
];
const filteredObjList = objList.filter(x => !idsToRemove.includes(x.id));
console.log(filteredObjList);
Turn the idsToRemove
into a Set
so that you can use Set.prototype.has
(an O(1)
operation), and .filter
the objList
just once, so that the overall complexity is O(n)
(and you only iterate over the possibly-huge objList
once):
var idsToRemove = ["3", "1"];
var objList = [{
id: "1",
name: "aaa"
},
{
id: "2",
name: "bbb"
},
{
id: "3",
name: "ccc"
}
];
const set = new Set(idsToRemove);
const filtered = objList.filter(({ id }) => !set.has(id));
console.log(filtered);
Note that Array.prototype.includes
and Array.prototype.indexOf
operations are O(N)
, not O(1)
, so if you use them instead of a Set
, they may take significantly longer.