js 数组去重 方法和思路

单个数组去重

  1. 创建第二个数组用来接收不重复元素

.indexOf()/lastIndexOf

let newArr = []
for (let item of arr) {
  if (newArr.indexOf(item) === -1) {
    newArr.push(item)
  }
  // 或者
  // if (newArr.findIndex(item))
  // if (newArr.includes(item))
}

使用reduce

arr.reduce((pre, item) => {
  if (pre.indexOf(item) === -1) {
    pre.push(item)
  }
  return pre
}, [])
  1. Set
[...new Set(arr)]
Array.from(new Set(myArray))

两个数组去重

  1. 可以先合并数组,再参照单个数组的情况

合并数组的方法

// 利用 apply 特性
arr.push.apply(arr, arr2)
// .concat
conArr = arr.concat(arr2)
// 遍历 push
// ... 三点运算符 ES6
conArr = [...arr,...arr2]

两个技巧

对象数组 去重

lodash _.difference

posted @ 2022-03-03 00:11  海胆Sur  阅读(16)  评论(0)    收藏  举报  来源