JS数组去重

  • A+
所属分类:JavaScript

1.过滤器和indexof

var arr = [2,3,4,4,5,2,3,6];
var arr2 = arr.filter(function(element,index,self){
  return self.indexOf(element) === index;
});
console.log(arr2); //[2, 3, 4, 5, 6]

2.循环和indexof

var arr = [2,3,4,4,5,2,3,6],
   arr2 = [];
for(var i = 0;i< arr.length;i++){
    if(arr2.indexOf(arr[i]) < 0){
        arr2.push(arr[i]);
    }
}
console.log(arr2);//[2, 3, 4, 5, 6]

3.把数组的值作为对象的键

var arr = [0,2,3,4,4,0,2];
var obj = {};
var tmp = [];
for(var i = 0 ;i< arr.length;i++){
   if( !obj[arr[i]] ){
      obj[arr[i]] = 1;
      tmp.push(arr[i]);
   }
}
console.log(tmp); //[0, 2, 3, 4]

4.利用数组的循环和includes方法

var arr = [0,2,3,4,4,0,2];
var res = [];
for(var i=0; i<arr.length; i++){
  if( !res.includes(arr[i]) ){ // 如果res新数组包含当前循环item
     res.push(arr[i]);
}
console.log(res);

5.利用数组的filter和includes

var arr = [0,2,3,4,4,0,2];
var res = [];
res = arr.filter(function(item){
    return res.includes(item) ? '' : res.push(item);
});

6.利用es6的set方法

var arr = [0,2,3,4,4,0,2];
var arr2=Array.from(new Set(arr));
console.log(arr2);

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的QQ
  • 我的QQ扫一扫
  • weinxin
avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: