如何基于check数组过滤arr数组,实现getItems函数的过滤逻辑
实现方案
核心逻辑
- 遍历原数组的所有元素,生成全新数组避免修改原数据
- 每个元素保留原有全部属性,仅对
cr子数组做过滤 - 过滤规则:仅保留
cr子元素的cc属性值存在于check数组中的条目 - 如果
check数组长度较大,可以提前转为Set将查询复杂度从O(n)降到O(1),提升运行效率
完整实现代码
let check = ["DIS_1","DIS_2","DIS_6","DIS_10"] let arr = [{otherProperty: "",cr: [{cc: "DIS_1", cv: "cal1"},{cc: "first", cv: "cal2"},{cc: "DIS_2", cv: "cal3"}]}, {otherProperty: "",cr: [{cc: "DIS_6", cv: "cal4"},{cc: "second", cv: "cal5"},{cc: "DIS_10", cv: "cal6"}]}, {otherProperty: "",cr: [{cc: "third", cv: "cal7"},{cc: "fourth", cv: "cal8"},{cc: "DIS_1", cv: "cal9"}]} ] let expectedOutput = [{otherProperty: "",cr: [{cc: "DIS_1", cv: "cal1"},{cc: "DIS_2", cv: "cal3"}]}, {otherProperty: "",cr: [{cc: "DIS_6", cv: "cal4"},{cc: "DIS_10", cv: "cal6"}]}, {otherProperty: "",cr: [{cc: "DIS_1", cv: "cal9"}]} ] // 提前转Set优化查询性能,数据量小也可以直接用check.includes const checkSet = new Set(check) function getItems(arr) { return arr.map(item => ({ // 展开保留原对象所有其他属性 ...item, // 过滤cr数组符合条件的条目 cr: item.cr.filter(crItem => checkSet.has(crItem.cc)) })) } console.log('expect', getItems(arr))
运行上述代码后,getItems(arr)的返回结果与你给出的expectedOutput完全一致。
内容的提问来源于stack exchange,提问作者chidananda
相关产品推荐
相关产品推荐

