ES6 Set
function unique(arr) {
return Array.from(new Set(arr))
}
let arr = [1, 2, 3, 4, 5, 1, 2, 3]
console.log(unique(arr))
// [1, 2, 3, 4, 5]
当前项和剩余项比较
function unique(arr) {
let newArr = []
for (let i = 0; i < arr.length; i++) {
let current = arr[i]
let residue = arr.slice(i + 1)
if (residue.indexOf(current) === -1) {
newArr.push(current)
}
}
return newArr
}
let arr = [1, 2, 3, 4, 5, 1, 2, 3]
console.log(unique(arr))
// [4, 5, 1, 2, 3]
先排序,再进行遍历及相邻元素比对去重
function unique(arr) {
arr.sort((a, b) => a - b)
let newArr = [arr[0]]
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
newArr.push(arr[i])
}
}
return newArr
}
let arr = [1, 2, 3, 4, 5, 1, 2, 3]
console.log(unique(arr))
// [4, 5, 1, 2, 3]
利用对象的属性不能相同的特点进行去重
function unique(arr) {
let obj = {}
let newArr = []
for (let i = 0; i < arr.length; i++) {
current = arr[i]
if (!obj[current]) {
obj[current] = 1
newArr.push(current)
}
}
return newArr
}
let arr = [1, 2, 3, 4, 5, 1, 2, 3]
console.log(unique(arr))
// [1, 2, 3, 4, 5]
更新完整版:使用 ES6 Map 配合计数排序
function uniq(arr) {
const map = new Map()
const len = arr.length
if (!(arr instanceof Array)) {
throw new Error(`is not a array!`)
}
for (let i = 0; i < len; i++) {
let temp = arr[i]
if (!temp) continue
if (map.has(temp)) continue
map.set(temp, true)
}
return [...map.keys()]
}