js实现数组去重的六种方法

方法一

使用数组的indexof方法,如果elementindex不相等则说明element相同,则过滤掉

Array.prototype.distinct1 = function () {
    return this.filter(function (element, index, self) {
        return self.indexOf(element) === index;
    });
}

方法二

ES6提供了数据结构Set。类似于数组,但是没有重复值。可以利用Set数据结构中值不能重复的特性去重

Array.prototype.distinct2 = function () {
    let set = new Set(this);
    return [...set];
}

方法三

遍历两个数组,将原数组的值和新数组的值一一进行比较,如果原数组的值不存在则加入新数组中

Array.prototype.distinct3 = function () {
    let result = [];
    for (let i of this) {
        let flag = 0;
        for (let j of result) {
            if (i === j) {
                flag = 1;
            }
        }
        if (flag === 0) {
            result.push(i);
        }
    }
    return result;    
}

方法四

先将数组进行排序,然后遍历数组,将数组中每个值与其后一个值比较,如果不同则存入新数组

Array.prototype.distinct4 = function () {
    var arr = this.sort();
    var result = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] != arr[i + 1])
            result.push(arr[i]);
    }
    return result;
}

方法五

js中数组也是对象,可以根据对象属性的特性。遍历数组,如果该值不是对象的属性,则在对象中添加等于该值的属性,并且同时把该值加入新数组

Array.prototype.distinct5 = function () {
    let result = [];
    let obj = {};
    for (let x of this) {
        if (!obj[x]) {
            obj[x] = x;
            result.push(x);
        }
    }
    return result;
}

方法六

双重循环遍历数组,如果值相同,使用splice方法删去后一个相同的值

Array.prototype.distinct6 = function () {
    let arr = this;
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] === arr[j]) {
                arr.splice(j, 1);
                j--;
            }
        }
    }
    return arr;
}

以上六种方法均可以实现数组去重,区别是性能不同,并且有的方法会改变数组的顺序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Dylan、

耕码不易,白嫖可耻

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

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

打赏作者

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

抵扣说明:

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

余额充值