JavaScript 高性能数组去重

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/qq_43168841/article/details/82954733

一、测试模版

数组去重是一个老生常谈的问题,网上流传着有各种各样的解法
为了测试这些解法的性能,我写了一个测试模版,用来计算数组去重的耗时

// distinct.js

let arr1 = Array.from(new Array(100000), (x, index)=>{
    return index
})

let arr2 = Array.from(new Array(50000), (x, index)=>{
    return index+index
})

let start = new Date().getTime()
console.log('开始数组去重')

function distinct(a, b) {
    // 数组去重
}

console.log('去重后的长度', distinct(arr1, arr2).length)

let end = new Date().getTime()
console.log('耗时', end - start)

这里分别创建了两个长度为 10W 和 5W 的数组

然后通过 distinct() 方法合并两个数组,并去掉其中的重复项

数据量不大也不小,但已经能说明一些问题了

二、Array.filter() + indexOf

这个方法的思路是,将两个数组拼接为一个数组,然后使用

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

遍历数组,并结合 indexOf 来排除重复项

function distinct(a, b) {
    let arr = a.concat(b);
    return arr.filter((item, index)=> {
        return arr.indexOf(item) === index
    })
}

这就是我被吐槽的那个数组去重方法,看起来非常简洁,但实际性能略差。

image

四、for…of + includes()

双重for循环的升级版,外层用 for…of 语句替换 for 循环,把内层循环改为 includes()

先创建一个空数组,当 includes() 返回 false 的时候,就将该元素 push 到空数组中

类似的,还可以用 indexOf() 来替代 includes()

function distinct(a, b) {
    let arr = a.concat(b)
    let result = []
    for (let i of arr) {
        !result.includes(i) && result.push(i)
    }
    return result
}

这种方法和 filter + indexOf 挺类似

只是把 filter() 的内部逻辑用 for 循环实现出来,再把 indexOf 换为 includes

所以时长上也比较接近

image

本次给大家推荐一个最后给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。
对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。
最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。

猜你喜欢

转载自blog.csdn.net/qq_43168841/article/details/82954733