为了账号安全,请及时绑定邮箱和手机立即绑定

JS实现数组去重方法总结

标签:
JavaScript

话不多说,我们这就进入正文。
第一种:使用forEach从传入参数的下一个索引值开始寻找是否存在重复,如果不存在重复则push到新的数组,达到去重的目的。

noRepeat = (repeatArray) => {    var result = [];
    repeatArray.forEach((value, index ,arr) => {  
        var isNoRepeat = arr.indexOf(value,index+1);  
        if(isNoRepeat === -1){
            result.push(value);
        }
    })    return result;
};

还可以换一种方式实现,利用新数组,遍历要去重的数组,判断通过遍历的数值是否在新数组里面存在,如果不存在,则push到新数组里面。代码如下:

noRepeat = (repeatArray) => {    var result = [];
    repeatArray.forEach((value, index ,arr) => {        if (result.indexOf(value) === -1 ) {
            result.push(value);
        }
    })    return result;
};

第二种:利用对象的属性不能重复的特点进行去重。

    noRepeat = (repeatArray) => {        var hash = {};        var result = [];
        repeatArray.forEach((value, index ,arr) => {            if (!hash[value]) {
                hash[value] = true;
                result.push(value);
            }
        })        return result;
    };

第三种:先将数组进行排序,然后通过对比相邻的数组进行去重。

    noRepeat = (repeatArray) => {
        repeatArray.sort();        var result = [];
        repeatArray.forEach((value, index ,arr) => {            if (value !== arr[index+1]) {
                result.push(value);
            }
        })        return result;
    };

第四种:利用ES6的Set新特性(所有元素都是唯一的,没有重复)。需要注意的是,可能存在兼容性问题。

    noRepeat = (repeatArray) => {        var result = new Set();
        repeatArray.forEach((value, index ,arr) => {
            result.add(value);
        })        return result;
    };

该方法处理多个数组的去重是相当的好用,代码如下:

let array1 = [1, 2, 3, 4];let array2 = [2, 3, 4, 5, 6];let noRepeatArray = new Set([... array1, ... array2]);console.log('noRepeatArray:', noRepeatArray);



作者:甜甜_饭
链接:https://www.jianshu.com/p/85ed71e7ddae


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消