美文网首页
JavaScript方法对数组元素去重

JavaScript方法对数组元素去重

作者: 游海东 | 来源:发表于2019-12-19 10:05 被阅读0次

    1. forEach函数 + indexOf方法

    function removeDouble(arr){
        let ns = [];
        arr.forEach(function(item,index,array){
            if(arr.indexOf(item) == index){
                ns.push(item);
            }
        })
        
        return ns;
    }
    
    let a = [1,3,4,5,6,2,3,1,4,6,7,8,9,0,2,1,3];
    let b = removeDouble(a);
    console.log(b);
    
    结果:
    [1, 3, 4, 5, 6, 2, 7, 8, 9, 0]
    

    2. for循环语句 + indexOf方法

    function removeDouble(arr){
        let ns = [];
        for (let i = 0; i < arr.length; i++) {
            if(ns.indexOf(arr[i]) == -1){
                ns.push(arr[i]);
            }
        }
        
        return ns;
    }
    
    let a = [1,3,4,5,6,2,3,1,4,6,7,8,9,0,2,1,3];
    let b = removeDouble(a);
    console.log(b);
    
    结果:
    [1, 3, 4, 5, 6, 2, 7, 8, 9, 0]
    

    3. filter函数方法

    function removeDouble(arr){
        let ns = [];
        ns = arr.filter(function(item,index,array){
            return arr.indexOf(item) == index;
        });
        
        return ns;
    }
    
    let a = [1,3,4,5,6,2,3,1,4,6,7,8,9,0,2,1,3];
    let b = removeDouble(a);
    console.log(b);
    
    结果:
    [1, 3, 4, 5, 6, 2, 7, 8, 9, 0]
    

    4. splice方法

    function removeDouble(arr){
        for (let i = 0; i < arr.length; i++) {
            for (let j = i+1; j < arr.length; j++) {
                if(arr[i] == arr[j]){
                    arr.splice(j,1);
                    j--;
                }
            }
        }
        
        return arr;
    }
    
    let a = [1,3,4,5,6,2,3,1,4,6,7,8,9,0,2,1,3];
    let b = removeDouble(a);
    console.log(b);
    
    结果:
    [1, 3, 4, 5, 6, 2, 7, 8, 9, 0]
    

    5. Set方法

    function removeDouble(arr){
        let ns = [];
        let set = new Set(arr);
        ns = [...set];
        
        return ns;
    }
    
    let a = [1,3,4,5,6,2,3,1,4,6,7,8,9,0,2,1,3];
    let b = removeDouble(a);
    console.log(b);
    
    结果:
    [1, 3, 4, 5, 6, 2, 7, 8, 9, 0]
    

    6. Set方法和Array.from方法

    function removeDouble(arr){
        return Array.from(new Set(arr));
    }
    
    let a = [1,3,4,5,6,2,3,1,4,6,7,8,9,0,2,1,3];
    let b = removeDouble(a);
    console.log(b);
    
    结果:
    [1, 3, 4, 5, 6, 2, 7, 8, 9, 0]
    

    相关文章

      网友评论

          本文标题:JavaScript方法对数组元素去重

          本文链接:https://www.haomeiwen.com/subject/voxmnctx.html