JS中数组去重的方式
方式一:Set(ES6)
let arr = [1,2,2,3,3,4,5,2];
const unique = arr => [...new Set(arr)];
console.log(unique(arr));
// [ 1, 2, 3, 4, 5 ]
方式二:reduce
let arr = [1,2,2,3,3,4,5,2];
const unique = (arr) =>{
return arr.sort().reduce((acc,cur) =>{
if(acc.length === 0 || acc[acc.length - 1] !== cur){
acc.push(cur);
}
return acc;
},[]);
}
console.log(unique(arr));
// [ 1, 2, 3, 4, 5 ]
方式三:filter
let arr = [1,2,2,3,3,4,5,2];
const unique = (arr) =>{
return arr.filter((element,index,array) =>{
return array.indexOf(element) === index
});
}
console.log(unique(arr));
// [ 1, 2, 3, 4, 5 ]
方式四:不产生新数组情况下,数组去重
let arr = [1,2,2,3,3,4,5,2];
const unique = (arr) =>{
let len = arr.length - 1;
for(let i = len;i >= 0;i --){
if(arr.indexOf(arr[i]) !== i){
arr[i] = arr[len --];
}
}
// 删除重复项
arr.splice(len + 1);
return arr;
}
console.log(unique(arr));
// [ 1, 2, 4, 3, 5 ]
参考文章:手写数组去重、扁平化函数