手写 数组去重

164 阅读1分钟

使用Set

function unip(target) {
  return [...new Set(target)]
}

var arr = [1, 2, , 2, '3', 3, 3, 3]
unip(arr) // [1,2,undefined,'3',3]

手写

  1. 使用计数排序的思路
  2. 使用Map,多类型去重
function unip(target) {
  const map = new Map()
  for (let i = 0; i <= target.length - 1; i++) {
    if (map.has(target[i])) {
      continue
    }
    map.set(target[i], true)
  }
  return [...map.keys()]
}

var arr = [1, 2, , 2, '3', 3, 3, 3]
unip(arr) // [1,2,undefined,'3',3]