1、set
const arr = [1, 2, 2, 3, 4, 5, 6, 4, 5]
const res = new Set([...arr])
console.log(res)
2、双重for循环
const arr = [1, 2, 2, 3, 4, 5, 6, 4, 5]
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(i, 1)
i--;
}
}
}
console.log(arr);
3、indexOf去重
const arr = [1, 2, 2, 3, 4, 5, 6, 4, 5]
const arr1 = []
for (let i = 0; i < arr.length; i++) {
if (arr1.indexOf(arr[i]) === -1) {
arr1.push(arr[i]);
}
}
console.log(arr1);
4、sort
const arr = [1, 2, 2, 3, 4, 5, 6, 4, 5, 6, 6, 6, 6]
arr.sort()
let arrry = [arr[0]];
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
arrry.push(arr[i]);
}
}
console.log(arrry);