js数组去重

//要领一:时刻复杂度为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())

我的微信民众号:天字一等

    原文作者:胡椒
    原文地址: https://segmentfault.com/a/1190000019329644
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞