我正在尝试通过Set.has
过滤数组,如下所示:
const input = [
{ nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' },
{ nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' },
{ nick: 'Some name', x: 22, y: 27, grp: 11, id: '19344' },
{ nick: 'Some name', x: 22, y: 30, grp: 11, id: '19350' },
{ nick: 'Some name', x: 22, y: 12, grp: 23, id: '19374' },
{ nick: 'Some name', x: 22, y: 29, grp: 23, id: '19377' }
];
const grpToOmit = [ 11, 23 ];
const groupToOmitSet = new Set(grpToOmit);
input.filter(it => {
console.log(groupToOmitSet.has(it.grp))
return !groupToOmitSet.has(it.grp);
});
console.log(input)
因此,我从grpToOmit
数组创建了唯一值的集合,然后在过滤器函数中对其进行了检查。
此过滤器不执行任何操作,尽管console.log(groupToOmitSet.has(it.grp))
控制台正确运行了几次(我在下一行使用oposit),输入数组也没有改变。
答案 0 :(得分:4)
.filter
产生一个新数组,它不会使现有数组发生突变。您需要将结果分配给变量。
const input = [
{ nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' },
{ nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' },
{ nick: 'Some name', x: 22, y: 27, grp: 11, id: '19344' },
{ nick: 'Some name', x: 22, y: 30, grp: 11, id: '19350' },
{ nick: 'Some name', x: 22, y: 12, grp: 23, id: '19374' },
{ nick: 'Some name', x: 22, y: 29, grp: 23, id: '19377' }
];
const grpToOmit = [ 11, 23 ];
const groupToOmitSet = new Set(grpToOmit);
const output = input.filter(it => {
return !groupToOmitSet.has(it.grp);
});
console.log(output)