目录
数组去重
使用es6中Set方法去去重
function chong(arr){
return Array.from(new Set(arr))
}
let arrone=[1,1,1,1,2,3,4,32,3,3,3,4,4,5,5,5,]
console.log(chong(arrone));//[ 1, 2, 3, 4, 32, 5 ]
注意使用Array.from(把其形式装换成数组的形式)函数,否则会返回一个Set的类数组。
function chong(arr){
return [...new Set(arr)]
}
let arrone=[1,1,1,1,2,3,4,32,3,3,3,4,4,5,5,5,]
console.log(chong(arrone));//[ 1, 2, 3, 4, 32, 5 ]
这种形式是es6的拓展运算符
使用数组的api sort去重
function chong(arr) {
// 判断是否是数组类型
if(!Array.isArray(arr)) {
console.log('请注意,这里输入的是数组类型');
return
}
// 进行数组的反转,注意这里会改变原有数组
arr = arr.sort();
let array = [];
for(let i = 0; i < arr.length; i++) {
if(arr[i] !== arr[i - 1]) {
array.push(arr[i])
}
}
return array;
}
let arrone =[1,1,1,1,2,3,4,32,3,3,3,4,4,5,5,5,]
console.log(chong(arrone)); //[ 1, 2, 3, 32, 4, 5 ]
使用es6的includes去重
function chong(arr) {
if(!Array.isArray(arr)) {
console.log('Type error');
return
}
let array = [];
for(i = 0; i < arr.length; i++) {
if(!array.includes(arr[i])) {
array.push(arr[i]);
}
}
return array;
}
let arrone = [1,1,1,1,2,3,4,32,3,3,3,4,4,5,5,5,]
console.log(chong(arrone)); //[ 1, 2, 3, 32, 4, 5 ]
利用for+indexOf去重
function ch