手写3中数组去重的方法

49 阅读1分钟
// 方法1:使用 Set 去重并转换为数组 
const arr5 = [1, 1, 2, 1, 2, 3, 3, 4, 4, 4, 5, 5, 5,6]
const arr8 = []
const arr6 = [...new Set(arr5)]
console.log(arr6);

// 方法2:filter过滤获取每个元素,只要是第一次出现必定是arr5.indexOf(item) = index
const arr7 = arr5.filter((item,index) => arr5.indexOf(item) === index)
console.log(arr7);

// 方法3:数组用for of遍历,判断新数组有没有就尾部追加
for(let ele of arr5){
  if(arr8.indexOf(ele) === -1){
    arr8.push(ele)
  }
}
console.log(arr8);