如何在JavaScript中查找数组内符合指定属性匹配规则的重复记录
问题排查与修复方案
原代码核心错误
- 直接对数组
verifiedRecordsAll调用.Some/.Gum/.Thing属性,数组本身无这些属性,取值均为undefined,判断条件恒为真,所有记录都会被误判为重复 - 缺少跨记录对比逻辑,没有将当前遍历的记录与数组内其他记录做匹配
- 没有排除自身对比的逻辑,且
duplicateRecords未初始化默认值,数组长度不足2时会返回undefined而非空数组
修复后代码
// 定义记录类型,符合TS类型规范,可根据实际业务调整属性类型 interface VerifiedRecord { Some: unknown; Gum: unknown; Thing: unknown; } identifyDuplicateRecords(verifiedRecordsAll: VerifiedRecord[]): VerifiedRecord[] { const duplicateRecords: VerifiedRecord[] = []; if (verifiedRecordsAll.length < 2) return duplicateRecords; verifiedRecordsAll.forEach((currentRecord, currentIdx) => { // 检查是否存在其他符合重复规则的记录 const isDuplicate = verifiedRecordsAll.some((compareRecord, compareIdx) => { // 跳过自身对比 if (currentIdx === compareIdx) return false; return currentRecord.Some === compareRecord.Some || currentRecord.Gum === compareRecord.Gum || currentRecord.Thing === compareRecord.Thing; }); if (isDuplicate) duplicateRecords.push(currentRecord); }); return duplicateRecords; }
逻辑说明
- 通过两次遍历的下标对比,直接跳过自身和自身匹配的场景,解决你发现的自身对比问题
- 使用
some方法做匹配检查,找到符合条件的记录后会提前终止遍历,性能更优 - 函数默认返回空数组,避免边界场景返回
undefined的异常问题
大数据量可选优化方案
如果待处理数组长度很大(超过1000条),可以用哈希统计优化时间复杂度到O(n),避免O(n²)的双重遍历:
identifyDuplicateRecords(verifiedRecordsAll: VerifiedRecord[]): VerifiedRecord[] { if (verifiedRecordsAll.length < 2) return []; // 统计每个属性值出现的次数 const countMap = { Some: new Map<unknown, number>(), Gum: new Map<unknown, number>(), Thing: new Map<unknown, number>() }; // 第一次遍历统计次数 verifiedRecordsAll.forEach(record => { countMap.Some.set(record.Some, (countMap.Some.get(record.Some) || 0) + 1); countMap.Gum.set(record.Gum, (countMap.Gum.get(record.Gum) || 0) + 1); countMap.Thing.set(record.Thing, (countMap.Thing.get(record.Thing) || 0) + 1); }); // 第二次遍历筛选重复记录 return verifiedRecordsAll.filter(record => countMap.Some.get(record.Some)! > 1 || countMap.Gum.get(record.Gum)! > 1 || countMap.Thing.get(record.Thing)! > 1 ); }
内容的提问来源于stack exchange,提问作者Rohn07
相关产品推荐
相关产品推荐

