如何避免循环重复?优化集合过滤逻辑的技术问询
集合过滤逻辑优化方案
原问题场景
现有一段集合过滤代码,逻辑是依次执行三次过滤规则,若前一次过滤结果为空则触发下一次,但三次过滤存在大量重复逻辑,且多次遍历集合影响性能,代码如下:
let rows = (collection || []).filter((item: any) => { const { country, year, productType, units, productSubtype } = item; const cond1 = unitsPlain.length ? unitsPlain.includes(units) : true; const cond3 = years.includes(year); const cond2 = country === value; const cond4 = productType === key && !productSubtype; return cond1 && cond2 && cond3 && cond4; }); if (!rows.length) { rows = collection.filter((item: any) => { const { country, year, productType, productSubtype } = item; const cond3 = years.includes(year); const cond2 = country === value; const cond4 = productSubtype === key && !productType; return cond2 && cond3 && cond4; }); } if (!rows.length) { rows = collection.filter((item: any) => { const { country, year, productType, productSubtype } = item; const cond3 = years.includes(year); const cond2 = country === value; const cond4 = productSubtype === key || productType === key; return cond2 && cond3 && cond4; }); }
优化思路
核心是尽量减少集合遍历次数,同时保留原逻辑的匹配优先级:先尝试匹配第一级规则,再第二级,若前两级都无匹配项,最后用第三级规则兜底。通过一次遍历完成前两级规则的匹配,仅在前两级无结果时才执行第三级过滤,避免重复遍历。
优化后的代码
const targetCollection = collection || []; const result: any[] = []; // 标记是否找到前两级规则的匹配项 let hasHighPriorityMatches = false; // 一次遍历完成前两级规则的匹配 for (const item of targetCollection) { const { country, year, productType, units, productSubtype } = item; // 提取公共条件,避免重复判断 const meetsCommonCond = country === value && years.includes(year); if (!meetsCommonCond) continue; // 第一优先级规则:units匹配 + productType为key且无productSubtype const isLevel1Match = (unitsPlain.length ? unitsPlain.includes(units) : true) && productType === key && !productSubtype; // 第二优先级规则:productSubtype为key且无productType const isLevel2Match = productSubtype === key && !productType; if (isLevel1Match || isLevel2Match) { result.push(item); hasHighPriorityMatches = true; } } // 前两级无匹配时,用第三级规则兜底 if (!hasHighPriorityMatches) { result.push(...targetCollection.filter(item => { const { country, year, productType, productSubtype } = item; return country === value && years.includes(year) && (productSubtype === key || productType === key); })); } const rows = result;
优化点说明
- 减少遍历次数:原代码最多遍历3次集合,优化后最多2次(前两级一次,第三级一次;若前两级有匹配则仅遍历1次)
- 复用公共逻辑:将
country === value和years.includes(year)提取为公共条件,避免重复判断 - 保留优先级逻辑:严格遵循原逻辑的匹配顺序,确保高优先级规则先生效
- 代码更简洁:消除重复的解构和条件代码,逻辑层次更清晰
内容的提问来源于stack exchange,提问作者Dalama
相关产品推荐
相关产品推荐

