// 方法1:排序+双指针
let arr = [1, 2, 1, 3, 5, 5, 4, 2, 4,3,5,4,7,8,9,5,4,6,1]
function removeDuplciation(arr) {
arr.sort((a, b) => a - b);
let slow = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[slow] != arr[i]) {
arr[++slow] = arr[i];
}
}
arr.splice(slow, arr.length - slow - 1)
}
// 方法2:利用Set集合
arr = [...new Set(arr)]
console.log(arr);
// 方法3:利用reduce
arr = arr.reduce((pre,cur)=>{
if(!pre.includes(cur))
{
console.log(pre);
pre.push(cur);
}
return pre;
},[])
JS实现数组去重
最新推荐文章于 2024-08-30 22:17:40 发布