JS实现数组去重常用的六种方法
点击打开视频讲解更详细
双重for循环去重
let arr = [1,2,3,4,3,2,3,5];
let unique = (arr)=>{
//第一层for循环 数组的前一项
for(var i=0; i<arr.length; i++){
//第二层for循环 数组后一项
for(var j=i+1; j<arr.length; j++){
if(arr[i] === arr[j]){
arr.splice(j,1);//删除反复元素
j--;//修改下标
}
}
}
return arr;
}
unique(arr);
console.log(arr);
includes实现数组去重
let arr = [1,3,5,3,5]
let newArr = [];
let unique = (arr)=>{
let newArr = [];//新数组,用来接管不反复的数组
for(var i=0; i<arr.length; i++){
if(! newArr.includes(arr[i])){
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(unique(arr));
indexOf实现数组去重
let arr = [1,3,4,5,3,4,5,32,4];
let newArr = [];
let unique = (arr)=>{
let newArr = [];//新数组,用来接管不反复的元素
for(var i=0; i<arr.length; i++){
if(newArr.indexOf(arr[i])===-1){
newArr.push(arr[i]);
}
}
rerurn newArr;
}
console.log(unique(arr));
利用set方法去重
let arr = [12,43,23,43,68,12];
let item = [...new Set(arr)];
console.log(item);//[12, 43, 23, 68]
ES6 Array.from()方法
console.log(Array.from(new Set(arr))) ;
console.log([...new Set(arr)]) ;
递归去重
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);
若对您有帮助,请点击跳转到B站一键三连哦!感谢支持