JS 数组去重

转载自:https://blog.csdn.net/chengxuyuan20100425/article/details/8497277

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        
        Array.prototype.unique1 = function () {
            var n = [];//一个新的临时数组
            for (var i = 0; i < this.length; i++) {//遍历当前数组
                //如果当前数组的第i已经保存进了临时数组,那么跳过,
                //否则把当前项push到临时数组里面
                if (n.indexOf(this[i]) == -1) n.push(this[i]);
            }
            return n;
        }
        /* 注意:1, '1'等不同类型的值可能对应到同一个下标而被去重,但实际应该保留。 把 hash 表的值改为一个数组,里面保存出现过的类型就行了。 */
        Array.prototype.unique2 = function () {
            //n为hash表,r为临时数组
            var n = {}, r = [], len = this.length, val, type;
            for (var i = 0; i < this.length; i++) {
                val = this[i];
                type = typeof val;
                if (!n[val]) {//如果hash表中没有当前项
                    n[val] = type;//存入hash表
                    r.push(val);//把当前数组的当前项push到临时数组里面
                } else if (n[val].indexOf(type) < 0) {
                    n[val] = type;
                    r.push(val);
                }
            }
            console.log("n: ", n);
            return r;
        }
        Array.prototype.unique3 = function () {
            var n = [this[0]];//结果数组
            for (var i = 1; i < this.length; i++) {//从第二项开始遍历
                if (this.indexOf(this[i]) == i) {
                    //如果当前数组的第i项在当前数组中第一次出现的位置不是i,
                    //那么表示第i项是重复的,忽略掉。否则存入结果数组
                    n.push(this[i]);
                }
            }
            return n;
        }
        /*  这个方法的思路是先把数组排序,然后比较相邻的两个值。 排序的时候用的JS原生的sort方法,JS引擎内部应该是用的快速排序吧。 最终测试的结果是此方法运行时间平均是第二种方法的三倍左右,不过比第一种和第三种方法快了不少。 */
        Array.prototype.unique4 = function () {
            this.sort();
            var n = [this[0]];
            for (var i = 1; i < this.length; i++) {
                if (this[i] !== n[n.length - 1]) {
                    n.push(this[i]);
                }
            }
            return n;
        }
        var arr = [1, 1, 2, 3, 1, 666, "11", "11", undefined, undefined, null, null, "", "", { 1: 2 }, { 1: 2 }];
        console.log("unique1", arr.unique1());
        console.log("unique2", arr.unique2());
        console.log("unique3", arr.unique3());
        console.log("unique4", arr.unique4());
        console.log();
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值