美文网首页
JavaScript - 数组去重

JavaScript - 数组去重

作者: zz77zz | 来源:发表于2018-08-09 21:48 被阅读48次

    数组去重

    1.for循环

    var myArray = [1, 2, 3, 4, 5, 2];
    
    function getArray(array) {
        var newArray = [];
        var i = 0, l = array.length
        for (; i < l; i++) {
            for (var j = i + 1; j < l; j++) {
                if (array[i] === array[j]) {
                    // i++ ++i的问题~~别忘记了
                    j = ++i;
                }
            }
            newArray.push(array[i]);
        }
        return newArray;
    }
    console.log(getArray(myArray));
    

    2.0 少了多少行代码~~~

    var arr = [0, 0, 1, 1, 2, 2]
    var result = [0, 0, 1, 1, 2, 2].filter((item, index) => arr.indexOf(item) === index)
    console.log(result);
    

    3.0 indexOf

    function getArray(array){
        var newArray = [];
        for(var i = 0; i < array.length; i++){
            if(newArray.indexOf(array[i]) == -1){
                newArray.push(array[i]);
            }      
        }
        return newArray;
     }
     var myArray = [1,2,3,4,5,2];
     console.log(getArray(myArray));
    

    4.0 map/forEach

    var arr = [1,2,3,4,5,2,3,2];
    function getArray(arr){
        var newArr = [];
        arr.map(function(item,index,arr){
            if(arr.indexOf(item,index+1) == -1){
                newArr.push(item)
            }
        })
        return newArr;
    }
    console.log(getArray(arr));
    
    1. ES6 Set() 方法
    new Set([1,2,3,4,5,2,3,2])
    

    相关文章

      网友评论

          本文标题:JavaScript - 数组去重

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