JavaScript如何删除categoryId存在于指定ID数组中的对象?有无ES6方案?
实现方案
最推荐的ES6简便写法(无副作用,返回新数组)
优先使用Array.prototype.filter配合Set实现,性能高写法简洁:
const categories = [1, 2, 5, 8]; const items = [ { title: 'Hello', description: 'whatever you want to be a description', categoryId: 1 }, { title: 'Hello', description: 'whatever you want to be a description', categoryId: 3 } ]; // 先把分类ID转成Set,查找效率远高于Array.indexOf/Array.includes const categoryIdSet = new Set(categories); // 过滤得到所有categoryId不在分类数组中的项 const filteredItems = items.filter(item => !categoryIdSet.has(item.categoryId));
执行后filteredItems的结果为:
[ { title: 'Hello', description: 'whatever you want to be a description', categoryId: 3 } ]
原地修改原数组的方案(不生成新数组)
如果必须修改原items数组而不能生成新数组,不要用正向循环+splice,避免数组下标偏移导致的漏项/死循环问题,用反向遍历即可:
const categoryIdSet = new Set(categories); // 从数组末尾往前遍历,删除元素不会影响未遍历的下标 for (let i = items.length - 1; i >= 0; i--) { if (categoryIdSet.has(items[i].categoryId)) { items.splice(i, 1); } }
内容的提问来源于stack exchange,提问作者Loth
相关产品推荐
相关产品推荐

