JS实现数组去重方法总结

话不多说,我们这就进入正文。
第一种:使用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);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容