JS 数组操作,找到某些项重复的数据。

556 阅读1分钟

在工作中可能需要在tableList数组中进行查重,但是数组不是简单的数组,因此总结下之前写的一些,值得记录的用法

操作数组

const list = [
    {a:'a123',b:'b141',c:'c453',d:'d657'},
    {a:'a234',b:'b141',c:'c453',d:'d798'},
    {a:'a789',b:'b234',c:'c789',d:'d901'},
    {a:'a123',b:'b141',c:'c453',d:'d897'},
    {a:'a432',b:'b321',c:'c432',d:'d322'},
    {a:'a141',b:'b234',c:'c789',d:'d890'}
];
const proplist = ['b','c'];

操作方法

一般情况下,我们会遍历数组,然后再遍历对象的key,获得我们想要的结果,但是这样的思路,增加了遍历次数,并且还不简洁。今天记录的是以另一种思路, 使用map的方法,比较重复性,减少对象内部的遍历次数增强,减少遍历损耗

let dupIndexObj = {
    indexList:[],
    dupStrList:[]
};
list.forEach((li1,index1) => {
    let indexArr = [index1];
    // 如果当前item的重复数据已经在之前遍历过了,就终止本次循环,减少无所谓的消耗。
    if(dupIndexObj.dupStrList.includes(proplist.map(k => li1[k]).join())) return;
    list.forEach((li2,index2) => {
        if(
            proplist.map(k => li1[k]).join() === proplist.map(k => li2[k]).join() && 
            index1 !== index2
        ) {
            indexArr.push(index2);
        }
    });
    if(indexArr.length >= 1) {
        indexArr.sort((a,b)=> (a-b)); // 对数组进行正序排序
        dupIndexObj.indexList.push(indexArr); // 收集重复数据在list中的index
        dupIndexObj.dupStrList.push(proplist.map(k => li1[k]).join());
    }
});

这样下来,我们可以把list中所有的重复数据的index获取到并分好组,即dupIndexObj.indexList,以供方便直接使用。