简体   繁体   中英

Remove object from array based on array of some property of that object

I have an array of objects (objList) that each has "id" property.

I have an array of strings (idsToRemove), representing IDs of the objects to remove from objList.

I find some solution but I fear it's slow, especially with the large list of objects with lots of properties. Is there more efficient way to do this?

 var idsToRemove = ["3", "1"]; var objList = [{ id: "1", name: "aaa" }, { id: "2", name: "bbb" }, { id: "3", name: "ccc" } ]; for (var i = 0, len = idsToRemove.length; i < len; i++) { objList = objList.filter(o => o.id != idsToRemove[i]); } console.log(objList);

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.

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

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()

Simply use Array.filter()

 const idsToRemove = ['3', '1']; const objList = [{ id: '1', name: 'aaa', }, { id: '2', name: 'bbb', }, { id: '3', name: 'ccc', } ]; const res = objList.filter(value => !idsToRemove.includes(value.id)); console.log("result",res);

I have created NPM package for this type of problems

Please refer to this:- https://www.npmjs.com/package/array-refactor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM