在JavaScript中,有多種方法可以實(shí)現(xiàn)數(shù)組去重。以下是一些常見的方法:
function uniqueArray(arr) {
return Array.from(new Set(arr));
}
const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
function uniqueArray(arr) {
return arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
}
const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
function uniqueArray(arr) {
return arr.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
}
const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
function uniqueArray(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
let isUnique = true;
for (let j = 0; j < result.length; j++) {
if (arr[i] === result[j]) {
isUnique = false;
break;
}
}
if (isUnique) {
result.push(arr[i]);
}
}
return result;
}
const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
以上方法都可以實(shí)現(xiàn)數(shù)組去重,你可以根據(jù)自己的需求和喜好選擇合適的方法。