如何在JavaScript中基于多列获取重复行的索引?
问题:匹配多列字段找出重复行索引
原始数据
const dummyData =[ { "plateID":"1234567", "freezer":"fridzer A", "shelf":"1", "box":"1", "position":"1", }, { "plateID":"1234567", "freezer":"fridzer B", "shelf":"1", "box":"1", "position":"1", }, { "plateID":"1234567", "freezer":"fridzer C", "shelf":"12", "box":"11", "position":"13", }, { "plateID":"1234567", "freezer":"fridzer A", "shelf":"1", "box":"1", "position":"1", }, { "plateID":"1234567", "freezer":"fridzer A", "shelf":"5", "box":"2", "position":"3", }, { "plateID":"1234567", "freezer":"fridzer C", "shelf":"12", "box":"11", "position":"13", }, ]
需求说明
需要同时匹配freezer、shelf、box、position这四个字段的值,找出所有重复行的索引,期望输出:
[ 0, 2, 3, 5 ]
尝试过的代码(仅支持单列匹配)
let duplicates = []; let tempArray = {}; dummyData.forEach((item, index) => { tempArray[item.freezer] = tempArray[item.freezer] || []; tempArray[item.freezer].push(index); }); for (var key in tempArray) { if (tempArray[key].length > 1) { duplicates = duplicates.concat(tempArray[key]); } console.log(duplicates); console.log(tempArray); }
解决方案
核心思路是把四个字段组合成唯一标识作为对象的键,以此判断四字段是否完全重复,具体实现如下:
let duplicates = []; // 存储每个字段组合对应的索引列表 const groupMap = {}; dummyData.forEach((item, index) => { // 用特殊字符分隔字段,避免拼接后产生歧义 const key = `${item.freezer}|${item.shelf}|${item.box}|${item.position}`; if (!groupMap[key]) { groupMap[key] = []; } groupMap[key].push(index); }); // 收集所有重复分组的索引 for (const key in groupMap) { if (groupMap[key].length > 1) { duplicates = duplicates.concat(groupMap[key]); } } // 按索引排序,匹配期望输出格式 duplicates.sort((a, b) => a - b); console.log(duplicates); // 输出 [0, 2, 3, 5]
说明
- 选用
|作为分隔符是为了避免不同字段值拼接后产生歧义,比如freezer: "a1"+shelf: "2"和freezer: "a"+shelf: "12",直接拼接会得到相同字符串,加分隔符就能区分开。 - 该方法时间复杂度为O(n),仅需两次遍历数组,效率较高。
内容的提问来源于stack exchange,提问作者souradeep Misra
相关产品推荐
相关产品推荐

