JS/VUE array deduplication method

Regarding the method of deduplication in an array, some say 10 kinds, some say 12 kinds, but there is nothing wrong with it. If there are 20 kinds of methods, there is nothing wrong with it. Everyone writes differently, so you can change the code. But, we don’t need so much, it’s OK to master the four main solution ideas
, here’s the following:
1. indexOf/includes
idea: compare the current item with the following content, delete it if it is included

let ary=[12,23,12,15,25,23,25,14,16];
for(let i=0;i<ary.length-1;i++){
    
    
 let item=ary[i],
 args=arr.slice(i+1){
    
    
 args=ary.slice(i+1);
if(args.indexOf(item)>-1){
    
      //是否包含 不包含-1
//包含:我们可以把当前项干掉
//splice删除 缺点
#1.原来数组改变,这样如果i继续++,则会产生数组塌陷
#2.性能不好:当前项一旦删除,后面项索引都要变
ary.splice(i,1);
i--;
//或者用
//赋值为null,但要用filter过滤去掉null
ary[i]=null;
 }
 }
ary=ary.filter(item=>item!==null); //该行是用到ary[i]=null才用的
console.log(ary)
}

2. The processing scheme of sorting first and then comparing adjacent items (based on regularity)

ary.sort((a,b)=>a-b);
ary=ary.join('@')+'@';
let reg=/(\d+@)\1*/g/,
arr=[];
arr.replace(reg,(val,group1)=>{
    
    
   arr.push(Number(group1.slice(0,group1.length-1)));
})

3. Object key-value pair
Idea: Take each item in the array and store it in a new container. If it has already been stored, delete the current item

let obj={
    
    };
for(let i=0;i<ary.length;i++){
    
    
  let item=ary[i];
if(typeof obj[item])!=='undefined'){
    
    
  ary[i]=ary[ary.length-1];
ary.length--;
i--;
contine;
 }
obj[item]=item;
}
obj=null;

4.set (es6 new features)

let ary=[12,23,12,15,25,23,25,14,16];
arr=Array.form(new Set(ary));

Guess you like

Origin blog.csdn.net/weixin_41262185/article/details/108210536