0
点赞
收藏
分享

微信扫一扫

数组去重有几种方式?

Mhhao 2021-09-30 阅读 57
web 前端
方法一:遍历比较
function unique(arr) {
    const res=[]
    arr.forEach(item => { //数组遍历
       if (res.indexOf(item) < 0) { //数组遍历
           res.push(item)
       }
    });
    return res
}
unique([20, 30, 30, 50, 4, 4]) //[20, 30, 50, 4]
方法二:ES6:Set
function unique(arr){
    return [...new Set(arr)]
}
console.log(unique([20, 30, 30, 50, 4, 4]))

总结:两者比较,遍历方法需要经过两层遍历,相对来说使用set方法性能更优。

举报

相关推荐

0 条评论