目录
一、Set
const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
function uni(source) {
return [...new Set(source)]
}
console.log(uni(target))
二、for循环+数组的indexOf方法
const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
function uni2(source) {
const newArray = []
for (let i = 0; i < source.length; i++) {
// 如果newArray中没有该元素,则添加;
if (newArray.indexOf(source[i]) === -1) {
newArray.push(source[i])
}
}
return newArray
}
let res = uni2(target)
conosole.log(res)
三、sort默认排序,当前元素与前一个元素对比
const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
function uni(source) {
const res = []
// 默认排序
const arr1 = source.sort()
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr1[i - 1]) {
res.push(arr1[i])
}
}
return res
}
let res = uni(target)
console.log(res)
四、两个for循环
注:此方法会改变原数组
const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
for (let i = 0; i < target.length; i++) {
for (let j = i + 1; j < target.length; j++) {
if (target[i] === target[j]) {
target.splice(j, 1)
// 删掉后,后面所有的元素的索引会减一,所以需要j--
j--
}
}
}
console.log(target)
五、使用数组reduce方法
const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
//默认值为[]空数组,Array.reduce返回的是一个新数组,直接将这个新数组返回
function unique(array) {
return array.reduce((arr, current) => {
if (arr.indexOf(current) === -1) {
arr.push(current)
}
return arr
}, [])
}
let res = unique(target)
console.log(res)