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())

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理