js数组去重

121 阅读1分钟

转载自:www.jianshu.com/p/fb4550a2d…

//方法一:时间复杂度为O(n)。通过创建空的obj对象,遍历数组的时候查找obj对象中是否有值,没有的话以该元素创建一个属性并赋值,同时遍历的数组元素push进res数组

Array.prototype.unique = function () {
    let obj = {};
    let res = [];
    for(let i = 0;i < this.length;i++){
        if(!obj[this[i]]){
            obj[this[i]] = {};   //json[this[i]]可以随意赋值
            res.push(this[i]);
        }
    }
    return res;
}
console.log([1,1,2,2,3].unique())   //[1,2,3]

//方法二: 将res数组中上一个元素与原数组中的每个元素进行比较,将不同于上一个元素的元素放入res数组中

Array.prototype.unique = function () {
  console.log(this)
  let res = [this[0]];
   for(let i = 0;i < this.length;i++){
       if(this[i] != res[res.length-1]){
           res.push(this[i]);
       }
   }
  return res;
}
console.log([1,1,2,2,3].sort().unique())