JS数组去重的各种方法(包括去重NaN和复杂数组类型,对象,正则表达式)

34 篇文章 0 订阅

测试数据:

let arr1 = [3, 1, [1], 1, [1], true, true, {}, '1', NaN, undefined, NaN, undefined, {}, null, null,new String('1'),new String('1')];


1. 两种for循环 + splice(耗时最长)不能正确去重NaN和Object的方法
Array.prototype.unique = function () {
    for (let i = 0; i < this.length; i++) {
        for (let j = i + 1; j < this.length; j++) {
            if (this[i] === this[j]) {
                this.splice(j, 1);
                j--;
            }
        }
    }
    return this;
}

2. forEach + indexOf 不能正确去重NaN和Object的方法
Array.prototype.unique = function () {
    let newArr = [];
    this.forEach((item) => {
        if (newArr.indexOf(item) === -1) {
            newArr.push(item);
        }
    })
    return newArr;
}

4. for + sort(sort有问题)带 sort 方法的只对纯number或者纯string类型有效,它无法区分1和'1',

因为它是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。
Array.prototype.unique = function () {
    let newArr = [];
    this.sort();
    for (let i = 0; i < this.length; i++) {
        if (this[i] !== this[i + 1]) {
            newArr.push(this[i]);
        }
    }
    return newArr;
}

5. forEach + includes 能正确去重NaN,不能去重复杂数据类型
Array.prototype.unique = function () {
    let newArr = [];
    this.forEach((item) => {
        if (!newArr.includes(item)) {
            newArr.push(item);
        }
    })
    return newArr;
}

6. forEach + map 能正确去重NaN,不能去重复杂数据类型
Array.prototype.unique = function () {
    let map = new Map();
    let newArr = new Array();
    this.forEach((item) => {
        if (!map.has(item)) {
            map.set(item, 1);
            newArr.push(item);
        }
    });
    return newArr;
}

7. Set 可以去掉重复的NaN,但是不能去掉重复的复杂数据类型
Array.prototype.unique = function () {
    return [...new Set(this)];
}

8. filter + hasOwnProperty + JSON.stringify  可以去掉重复的NaN,重复的复杂数据类型,但是不能去掉正则表达式,还会丢失正则表达式
Array.prototype.unique = function () {
    let obj = {};
    return this.filter(function (item, index, arr) {
        return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true);
    });
}

9. filter + hasOwnProperty + JSON.stringify  可以去掉重复的NaN,重复的复杂数据类型,正则表达式
Array.prototype.unique = function () {
    let obj = {};
    return this.filter(function (item, index, arr) {
        let key = typeof item + JSON.stringify(item)+item;
        return obj.hasOwnProperty(key) ? false : (obj[key] = true);
    });
}

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值