在 JavaScript 中,有多種方法可以對(duì)數(shù)組進(jìn)行去重。以下是一些建議的方法:
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]
以上方法都可以實(shí)現(xiàn)數(shù)組去重,你可以根據(jù)自己的需求和喜好選擇合適的方法。