At ordinary times, we often encounter the need to remove the array, so here we sort out what methods can achieve the array to remove the need.

1. Double-layer for loop

    function removeSameEle(arr){
        let res=[]; 
        for(var i=0,len=arr.length; i<len; i++){for(var j=0,resLen=res.length; j<resLen; j++){if(arr[i]===arr[j]){// Check whether the data already exists in the result
                    break; }}// Determine if the end of the res has been executed
            if(j===resLen){ res.push(arr[i]); }}return res;
    }
Copy the code

2. Indexof or includes

    function removeSameEle(arr){
        let res=[];
        for(var i=0,len=arr.length; i<len; i++){//if(! res.includes(arr[i])){
            if(res.indexof(arr[i])<0) {// Check whether the data exists in the result
                res.push(arr[i])
            }
        }
        return res;
    }
Copy the code

3, the filter

    function removeSameEle(arr){
        let res=arr.filter((item,index,arr) = >{
            return arr.indexOf(item)===index;
        });
        return res;
    }
Copy the code

4. The unique value of reduce is deduplicated

    function removeSameEle(arr){
        return arr.reduce((accu,cur) = >{
                returnaccu.includes(cur)? [...accu]:[...accu,cur] },[]) }) }Copy the code

5, set the unique value of the deduplication

    function removeSameEle(arr){
        return [...new Set(arr)];
    }
Copy the code

6. Map deduplication

    function removeSameEle(arr){
        let map=new Map(a);let res=[];
        for(let i=0; len=arr.length; i<len; i++){if(!map.has(arr[i])){
                map.set(arr[i],arr[i]);
                res.push(arr[i]);
            }
        }
        return res;
    }
Copy the code

7, sort sort

function removeSameEle(arr){
    let res=[];
    let sortedArr=arr.sort();
    for(let i=0,len<sortedArr.length; i<len- 1; i++){if(i==0||sortedArr[i]! ==sortedArr[i+1]){
            res.push(sortedArr[i]);
             if(i===(len2 -)){
                res.push(sortedArr[i+1]); }}}return res;
}
Copy the code

8, use object.keys() to remove weights

    function removeSameEle(arr){
        let res=[];
        let obj={};
        arr.forEach((item,index) = >{
            if(! obj[item]){ obj[item]=item } });for(let value of Object.values(obj)){
            res.push(value);
        }
        return res;
    }
Copy the code