ReactJS中用数组过滤对象数组结果不符的修复方法
问题:修正数组过滤逻辑以得到预期结果
原代码
const data = [ { id: 1, serviceId: 1, title: "A" }, { id: 2, serviceId: 3, title: "T" }, { id: 3, serviceId: 45, title: "R" }, { id: 4, serviceId: 55, title: "Q" }, { id: 5, serviceId: 58, title: "S" }, { id: 6, serviceId: 63, title: "zx" }, { id: 7, serviceId: 66, title: "y" } ]; const secondData = [55, 66, 1, 58]; // 当前过滤代码 const myArrayFiltered = data.filter((el) => { return secondData.some((f) => { return f === el.serviceId; }); });
当前结果与预期差异
- 当前返回:保留
serviceId存在于secondData中的元素[ {id: 1, serviceId: 1, title: "A" }, { id: 4, serviceId: 55, title: "Q" }, { id: 5, serviceId: 58, title: "S" }, { id: 7, serviceId: 66, title: "y" } ] - 预期返回:保留
serviceId不在secondData中的元素[ { id: 2, serviceId: 3, title: "T" }, { id: 3, serviceId: 45, title: "R" }, { id: 6, serviceId: 63, title: "zx" } ]
修正方案
方案1:反转判断逻辑
直接在some的结果前加取反运算符!,将“保留存在的元素”改为“排除存在的元素”:
const myArrayFiltered = data.filter((el) => { return !secondData.some((f) => { return f === el.serviceId; }); });
方案2:使用Set提升性能(推荐)
将secondData转为Set,利用has方法的O(1)查询效率,避免数组多次遍历(数据量大时优势明显):
const serviceIdSet = new Set(secondData); const myArrayFiltered = data.filter(el => !serviceIdSet.has(el.serviceId));
内容的提问来源于stack exchange,提问作者someone
相关产品推荐
相关产品推荐

