数组去重的5种方法

1·new Set 解构

let res1 = [...new Set(arAr)]

2·new Set  Array.from

let res2 = Array.from(new Set(arAr))

3·for循环 splice

 1 let fn = (array) => {
 2   for (let i = 0; i < array.length; i++) {
 3     for (let j = i + 1; j < array.length; j++) {
 4       if (array(i) === array[j]) {
 5         array.splice(j, 1)
 6       }
 7     }
 8   }
 9   return array
10 }

4·indexOf   或者 includes

let fn = (array) => {
  let empty = []
  array.forEach((val, idx) => {
    // if (empty.indexOf(val) === -1) {
    //   empty.push(val)
    // }
    if (!empty.includes(val)) {
      empty.push(val)
    }
  })
  return empty
}

5·reduce

let fn = (array) => {
  array.reduce((pre, cur) => {
    return pre.indexOf(cur) === -1 ? pre.concat(cur) : [...pre]
  }, [])
}

 6·对象的唯一性 (性能最好)

 1 let fn = (array) => {
 2   let obj = {}
 3   let arr = []
 4   for(let i of array) {
 5     if (!obj[i]) {
 6       arr.push(i)
 7       obj[i] = 1
 8     }
 9   }
10   return arr
11 }

 关于常用的几种方法的性能;https://www.cnblogs.com/wisewrong/p/9642264.html

posted @ 2023-06-15 16:48  行屰  阅读(71)  评论(0编辑  收藏  举报