码迷,mamicode.com
首页 > 编程语言 > 详细

数组去重

时间:2018-02-20 21:39:23      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:跳过   tin   cti   dex   ++   his   ons   span   func   

一:用双层for循环+push

(双层循环,外层循环元素,内层循环时比较值;如果有相同的值则跳过,不相同则push进数组)

Array.prototype.distinct = 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 arra = [1, 2, 3, 4, 4,  2, 1, 1];
arra.distinct();
console.log(arra.distinct());   //返回[3,4,2,1]

 

二:利用splice直接在原数组进行操作

(外层循环元素,内层循环时比较值; 值相同时,则删去这个值)

 

Array.prototype.distinct = 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 a = [1, 5, 3, 2, 4, 4, 1, 2, 1, 1, 1, ];
var b = a.distinct();
console.log(b.toString()); //1,5,3,2,4

 

三:利用indexOf以及forEach

Array.prototype.distinct = function() {
       var arr = this,
       result = [],
       len = arr.length;
       arr.forEach(function(v, i, arr) {             //这里利用map,filter方法也可以实现
            var bool = arr.indexOf(v, i + 1);        //从传入参数的下一个索引值开始寻找是否存在重复
                  if(bool === -1) {
                         result.push(v);
                  }
        })
       return result;
};
var a = [ 1, 1, 2, 2, 3, 3, 2, 1];
var b = a.distinct();
console.log(b.toString()); //3,2,1

 

四:利用ES6的set

function dedupe(array) {
       return Array.from(new Set(array));
}
dedupe([1, 1, 2, 3]) 
let arr = [1, 2, 3, 3];
let resultarr = [...new Set(arr)];   //拓展运算符(...)内部使用for...of循环
console.log(resultarr); //[1,2,3]

 

数组去重

标签:跳过   tin   cti   dex   ++   his   ons   span   func   

原文地址:https://www.cnblogs.com/xuanranit/p/8455841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!