1. 利用 for 嵌套 for,然后 splice 去重
function cleanRepeat(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
let arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1,2, 5, 6, 9, 6, 2, 1, 5, 5];
console.log(cleanRepeat(arr1));
2. 利用 es6 Set 去重
function cleanRepeat(arr) {
return Array.from(new Set(arr));
}
let arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1, 2, 5, 6, 9, 6, 2, 1, 5, 5]
console.log(cleanRepeat(arr1));
function cleanRepeat(arr) {
return [...new Set(arr)]
}
let arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1, 2, 5, 6, 9, 6, 2, 1, 5, 5]
console.log(cleanRepeat(arr1));
3. 利用 sort 去重
function cleanRepeat(arr) {
if(!Array.isArray(arr)) {
console.log('Type error');
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 arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1,2, 5, 6, 9, 6, 2, 1, 5, 5]
console.log(cleanRepeat(arr1));
4. 利用 includes 去重
function cleanRepeat(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 arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1,2, 5, 6, 9, 6, 2, 1, 5, 5]
console.log(cleanRepeat(arr1));
5. 利用 for + indexOf 去重
function cleanRepeat(arr) {
if (!Array.isArray(arr)) {
console.log('Type error');
return
}
let newArr = [];
for(let i = 0; i < arr.length; i++) {
if(newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i])
}
}
return newArr
}
let arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1,2, 5, 6, 9, 6, 2, 1, 5, 5]
console.log(cleanRepeat(arr1));
6. 利用 forEach + indexOf 去重
function cleanRepeat(arr) {
if (!Array.isArray(arr)) {
console.log('Type error');
return
}
let newArr = [];
arr.forEach(val => {
if(newArr.indexOf(val) == -1) {
newArr.push(val);
}
})
return newArr
}
let arr1 = [1, 2, 3, 5, 4, 8, 7, 8, 5, 1, 2, 5, 6, 9, 6, 2, 1, 5, 5]
console.log(cleanRepeat(arr1));