美文网首页
JS数组去重

JS数组去重

作者: 酷鼠666 | 来源:发表于2018-07-04 10:53 被阅读0次

    方法1:两层for循环,外层循环原数组,内层循环时进行比较。

    Array.prototype.removal = function(){
     var arr = this,
      result = [],
      i,
      j,
      len = arr.length;
     for(i = 0; i < len; i++){
      for(j = i + 1; j < len; j++){
        if(arr[i] === arr[j]){
        j = ++i;
        }
      }
      result.push(arr[i]);
     }
     return result;
    }
    var arr1 = [1,2,3,4,2,3,1,4,5,6,6];
    arr1.removal();//返回[2,3,1,4,5,6]
    

    方法2:利用对象的属性不能相同的特点去重

    Array.prototype.removal = function(){
     var arr = this,
     i,
     obj = {},
     result = [],
     len = arr.length;
     for(i = 0; i < len; i++){
       if(!obj[arr[i]]){
         obj[arr[i]] = 1;
         result.push(arr[i]);
       }
     }
     return result;
    }
    var arr1 = [1,2,3,4,2,3,1,4,5,6,6];
    arr1.removal();//返回[1,2,3,4,5,6]
    

    方法3:利用splice直接在原数组进行操作

    Array.prototype.removal = function(){
     var arr = this,
     i,
     j,
     len = arr.length;
     for(i = 0; i < len; i++){
        for(j = i + 1; j < len; j++){
           if(arr[i] == arr[j]){
             arr.splice(j,1);
             len--;
             j--;
           }
        }
     }
     return arr;
    }
    var arr1 = [1,2,3,4,2,3,1,4,5,6,6];
    arr1.removal();//返回[1,2,3,4,5,6]
    

    方法4:数组递归去重

    Array.prototype.removal = function(){
     var arr = this,
     len = arr.length;
     arr.sort(function(a,b){
        return a - b;
     })
     function loop(index){
       if(index >= 1){
         if(arr[index] === arr[index-1]){
           arr.splice(index,1);
         }
         loop(index - 1); 
       }
     }
     loop(len-1);
     return arr;
    }
    var arr1 = [1,2,3,4,2,3,1,4,5,6,6];
    arr1.removal();//返回[1,2,3,4,5,6]
    

    方法5:利用indexOf以及forEach

    Array.prototype.removal = function (){
     var arr = this,
      result = [],
      len = arr.length;
     arr.forEach(function(v, i ,arr){  
      var bool = arr.indexOf(v,i+1);  
      if(bool === -1){
       result.push(v);
      }
     })
     return result;
    };
    var arr1 = [1,2,3,4,2,3,1,4,5,6,6];
    arr1.removal();//返回[1,2,3,4,5,6]
    

    方法6.利用ES6的set

    function removal(arr){
     return Array.from(new Set(arr));
    }
    removal([1,2,3,4,2,3,1,4,5,6,6]);//返回[1,2,3,4,5,6]
    

    相关文章

      网友评论

          本文标题:JS数组去重

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