前端-js-数组对象去重方法

数组对象去重

题目:

// 输入
[false, true, 1, 2, '1', '2', {}, {}, NaN, NaN, undefined, null].uniq();
// 获得
[false, true, 1, 2, '1', '2', {}, {}, NaN, undefined, null]

解决方法:

方法1:

Array.prototype.uniq = function () {
    // 先排除不符合条件
    if (!this.length || this.length == 0) return this;
    let arr = [], hasNaN = false, key, temp = {}, length = this.length;
    for (let i = 0; i<length; i++) {
        if (typeof this[i] == 'object') {
            // 对象直接放进去,因为引入类型指向堆栈不同
            arr.push(this[i])
        } else if (this[i] != this[i]) {
            // 此处判断是否是NaN,并且NaN未放入
            // NaN原型为Number,指的是非数字,所以NaN == NaN返回的是false,因为两个都是非数字,但不能说它们就相等,也可能一个是字符串,一个是数组呢
            if (!hasNaN) {
                // 此处必须把hasNaN的校验放到里面来,不然会的话,会NaN的校验在第二个if条件不符合后会进入第三个,从而出现多个NaN
                arr.push(this[i]);
            	hasNaN = true;
            }
        } else {
            // 其他类型
            // 进行鉴重校验,如果temp中不存在该key,则放入arr
            // key为类型加值本身,防止数字和字符串的重复
            key = typeof(this[i]) + this[i];
            if (!temp[key]) {
                arr.push(this[i]);
                temp[key] = true;
            }
        }
    }
    return arr;
}

方法2:

方法2区别与方法1在于使用Map来过滤重复。

// 输入
[false, true, 1, 2, '1', '2', {}, {}, NaN, NaN, undefined, null].uniq();
// 获得
[false, true, 1, 2, '1', '2', {}, {}, NaN, undefined, null]

Array.prototype.uniq = function () {
    // 先排除不符合条件
    if (!this.length || this.length == 0) return this;
    let arr = [], hasNaN = false, map = new Map(), length = this.length;
    for (let i = 0; i<length; i++) {
        if (typeof this[i] == 'object') {
            // 对象直接放进去,因为引入类型指向堆栈不同
            arr.push(this[i])
        } else if (this[i] != this[i]) {
            // 此处判断是否是NaN,并且NaN未放入
            // NaN原型为Number,指的是非数字,所以NaN == NaN返回的是false,因为两个都是非数字,但不能说它们就相等,也可能一个是字符串,一个是数组呢
            if (!hasNaN) {
                // 此处必须把hasNaN的校验放到里面来,不然会的话,会NaN的校验在第二个if条件不符合后会进入第三个,从而出现多个NaN
                arr.push(this[i]);
            	hasNaN = true;
            }
        } else {
            // 其他类型
            // Map可以存放键值对集合,且键不仅限于字符串,可以是任何类型,比起方法1省去了key值的构建
            key = this[i];
            if (!map.get(key)) {
                arr.push(this[i]);
                map.set(key, true)
            }
        }
    }
    return arr;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值