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

js数组去重

时间:2018-05-24 12:00:56      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:this   get   方法   bre   indexof   对比   ++   判断   set   

1.这个是通过js 中的reduce()方法进行数组去重

let d = arr.reduce((NewArray,n)=>{
    if(NewArray.indexOf(n) === -1){
        NewArray.push(n)
    }
    return NewArray;
},[])

2.通过双重循环,进行对比去重

Array.prototype.unique = function () {
  let newArray = [];
  let isRepeat;
  for (let i = 0; i < this.length; i++) {
    isRepeat = false;
    for (let j = 0; j < newArray.length; j++) {
      if (this[i] === newArray[j]) {
        isRepeat = true;
        break;
      }
    }
    if (!isRepeat) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}

3.通过map的get,set方式来判断去重

Array.prototype.quchong = function () {
    let newArray = [];
    let NewMap = new Map();
    for(let i = 0; i < this.length; i++){
        if(!NewMap.get(this[i])){ 
            NewMap.set(this[i], 1); //将数组中的每一项设置为key,然后value设置为固定的,这样在get的时候就能有区别了
            newArray.push(this[i]);
        }
    }
    return newArray;
}

 4 运用new Set 方法

var a = [‘hahha‘,‘hahha‘,3,4,5,5];
var bb = new Set(a);
console.log(bb);

 

js数组去重

标签:this   get   方法   bre   indexof   对比   ++   判断   set   

原文地址:https://www.cnblogs.com/Super-Zhen-/p/9081398.html

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