Js 数组去重 - Hash方法

本文介绍两种JavaScript方法来检查数组中是否存在重复元素。一种方法仅返回布尔值,另一种则返回去除重复后的数组。这两种方法都利用了哈希表来提高效率。

1 . 只做判断无返回数组时,可用如下方法:

function isRepeat(arr){
        var hash = {}, type = '';
        for(var i in arr){
            type = Object.prototype.toString.call(arr[i]);
            if(hash[arr[i] + type]){
                return true;
            }
            hash[arr[i] + type] = true;
        }
        return false;
    }

调用方法:
var arr = [1234567, 123, 123, 1, '1'];
$("#id").val(isRepeat(arr));

2 . 需返回结果时,可用如下方法:

function isRepeatReturn(arr){
    var hash = {}, result = [], type = '';
    for(var i in arr){
        type = Object.prototype.toString.call(arr[i]);
        if ( !hash[arr[i] + type] ) {
        hash[arr[i] + type] = true;
        result.push(arr[i]);
      }
    }
    return result;
}

或者:

if (!Array.prototype.unique) {
    Array.prototype.unique = function () {
        var hash = {}, result = [], type = '';
        for (var i = 0; i < this.length; i++) {
            type = Object.prototype.toString.call(this[i]); 
            if ( !hash[this[i]+ type] ) {
                hash[this[i]+ type] = true;
                result.push(this[i]);
            }
        }
        return result;
    };
}

调用方法:
var arr = [0, 1, '1', true, 5, true, false, undefined, undefined, null, null];
$("#result").val(isRepeatReturn(arr));
$("#result").val(arr.unique());

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ythook

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值