Skip to content

数组去重

🕒 Published at:

数组去重的基本方法

利用object中key的唯一性

js
function unique(arr) {
  let temp = {}
  let len = arr.length
  const ans = []
  for (let i = 0; i < len; i++) {
    if (!temp[arr[i]]) {
      temp[arr[i]] = 'abc'
      ans.push(arr[i])
    }
  }
  temp = null
  len = null
  return ans
}

使用Set进行数组去重

js
function unique(arr) {
  return Array.from(new Set(arr))
}

数组去重的其他方法

lodash-es 里的 uniqBy 和 uniqWith 方法