使用 Set
let arr = [1, 5, 2, 3, 4, 2, 3, 1, 3, 4]
const unique = (array) => {
return [...new Set(array)]
//或者 return Array.from(new Set(array))
}
unique(arr) //[1, 5, 2, 3, 4]
缺点:API太新,旧浏览器不支持;无法去掉重复的{}空对象。
使用 Map
let arr = [1, 5, 2, 3, 4, 2, 3, 1, 3, 4]
unique = (array) => {
let map = new Map();
let result = []
for (let i = 0; i < array.length; i++) {
if (map.has(array[i])) { // 判断 map 中是否已有该 key
continue
} else { // 如果 map 中没有该 key,就加入 result 中
map.set(array[i], true);
result.push(array[i]);
}
}
return result;
}
unique(arr) //[1, 5, 2, 3, 4]
缺点:API 太新,旧浏览器不支持;它与 Set 的数据结构比较相似,无法去掉重复的{}空对象。
使用 indexOf
let arr = [1, 5, 2, 3, 4, 2, 3, 1, 3, 4]
const unique = (array) => {
const result = []
for (let i = 0; i < array.length; i++) {
if (result.indexOf(array[i]) < 0) {
result.push(array[i])
}
}
return result
}
unique(arr) //[1, 5, 2, 3, 4]
缺点:如果数组中有重复的 NaN 时,indexOf 并不会处理 NaN。
借鉴计数排序的原理
let arr = [1, 5, 2, 3, 4, 2, 3, 1, 3, 4]
const unique = (array) => {
const hash = []
for (let i = 0; i < array.length; i++) {
hash[array[i]] = true
}
const result = []
for (let k in hash) {
result.push(k)
}
return result
}
unique(arr)
缺点:只支持数字或者字符串数组,如果数组里面有对象,比如 array = [{number:1}, 2],就会出错。