数组去重有几种方式?

Mhhao

关注

阅读 58

2021-09-30

方法一:遍历比较
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)

0 0 举报