手写数组去重 2022-03-28 面试题 167 words 1 min read Contents 1 Set 2 计数排序 3 Map 1 Set 1 2 3 const uniq = (arr) => Array.from(new Set(arr)) // or const uniq = (arr) => [...new Set(arr)] 2 计数排序 1 2 3 4 5 6 7 8 9 10 11 const uniq = (arr) => { if(!arr.length) return [] const map = {} for(let i = 0; i <= arr.length; i++) { if(!arr[i] || map[arr[i]]) continue // 利用对象中key值的唯一性 map[arr[i]] = true } // 仅支持字符串输出,且无法区分'1'和1 return Object.keys(map) } 3 Map 1 2 3 4 5 6 7 8 9 10 const uniq = (arr) => { if(!arr.length) return [] const map = new Map() for(let i = 0; i <= arr.length; i++) { if(!arr[i] || map.has(arr[i])) continue map.set(arr[i], true) } // 唯一缺点是兼容性差 return [...map.keys()] } Author gsemir LastMod 2022-03-28