示例数组:
let arr = [8,5,12,8,5,45,2,56,78,45,5,45],
let newArr = [];
方法一:暴力双循环
for(let i = 0;i < arr.length;i++){
for(let j = i + 1;j < arr.length;j++){
if(arr[i] == arr[j]){
arr.splice(j,1)
j--
}
}
}
console.log(arr) // (7) [8, 5, 12, 45, 2, 56, 78]
方法二:includes()去重
for(let i of arr){
if(!newArr.includes(i)){
newArr.push(i)
}else{
console.log(i + "重复了")
}
}
console.log(newArr) // (7) [8, 5, 12, 45, 2, 56, 78]
方法三:filter()循环过滤
arr.filter((val,index) => {
if(newArr.indexOf(val) < 0){
newArr.push(val)
}
})
console.log(newArr) // (7) [8, 5, 12, 45, 2, 56, 78]
方法四:sort()排序
arr = arr.sort() // (12) [12, 2, 45, 45, 45, 5, 5, 5, 56, 78, 8, 8]
for(let i = 0;i < arr.length;i++){
if(i <= arr.length - 1 && arr[i] != arr[i + 1]){
newArr.push(arr[i])
}
}
console.log(newArr) // (7) [12, 2, 45, 5, 56, 78, 8]
方法五:ES6 Array.from()
console.log(Array.from(new Set(arr))) // (7) [8, 5, 12, 45, 2, 56, 78]
console.log([...new Set(arr)]) // (7) [8, 5, 12, 45, 2, 56, 78](简写方法)
方法六:递归
let index = 0
arr = arr.sort()
function loop(index){
if(index > 1){
if(arr[index] == arr[index - 1]){
arr.splice(index,1)
}
index--
loop(index)
}
}
loop(arr.length - 1)
console.log(arr) // (7) [12, 2, 45, 5, 56, 78, 8]