1、ES6 Set
const arr = [1, 2, 1, 2, 3 ,4, 5]
const unique = (arr) => {
return Array.from(new Set(arr)) // return [...new Set(arr)]
}
unique(arr)
2、利用indexOf、includes
const arr = [1, 2, 1, 2, 3 ,4, 5]
const unique = (arr) => {
let result = []
for (let i of arr) {
if (result.indexOf(i) === -1) { // if (!result.includes(i))
result.push(i)
}
}
return result
}
unique(arr)
3、for 循环嵌套
const arr = [1, 2, 1, 2, 3 ,4, 5]
const unique = (arr) => {
for (let i = 0, len = arr.length; i < len; i++) {
for(let j = i + 1, len = arr.length; j < len; j++) {
if(arr[i] === arr[j]) {
arr.splice(i, 1)
j--
}
}
}
return arr
}
unique(arr)
复制代码
4、filter + indexOf
const arr = [1, 2, 1, 2, 3 ,4, 5]
const unique = (arr) => {
return arr.filter((item, index) => arr.indexOf(item) === index)
}
unique(arr)
5、reduce + includes
const arr = [1, 2, 1, 2, 3 ,4, 5]
const unique = (arr) => {
return arr.reduce((prev, curr) => prev.includes(curr) ? prev : [...prev, curr], [])
}
unique(arr)
6、sort
const arr = [1, 2, 1, 2, 3 ,4, 5]
const unique = (arr) => {
arr = arr.sort()
let result = [arr[0]]
for (let i = 1, len = arr.length; i < len; i++) {
if (arr[i] !== arr[i-1]) {
result.push(arr[i])
}
}
return result
}
unique(arr)