在JavaScript中,有多種方法可以實(shí)現(xiàn)數(shù)組去重。以下是一些常用的策略:
function uniqueArray(arr) {
return Array.from(new Set(arr));
}
const array = [1, 2, 2, 3, 4, 4, 5];
const unique = uniqueArray(array);
console.log(unique); // [1, 2, 3, 4, 5]
Set對象允許你存儲唯一的值,因此我們可以將數(shù)組轉(zhuǎn)換為Set對象,然后再將其轉(zhuǎn)換回?cái)?shù)組。
function uniqueArray(arr) {
return arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
}
const array = [1, 2, 2, 3, 4, 4, 5];
const unique = uniqueArray(array);
console.log(unique); // [1, 2, 3, 4, 5]
filter方法會創(chuàng)建一個(gè)新數(shù)組,其中包含通過測試的所有元素。在這個(gè)例子中,我們檢查每個(gè)元素在數(shù)組中的第一個(gè)索引是否與其當(dāng)前索引相同。如果不同,說明它是唯一的。
function uniqueArray(arr) {
return arr.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
}
const array = [1, 2, 2, 3, 4, 4, 5];
const unique = uniqueArray(array);
console.log(unique); // [1, 2, 3, 4, 5]
reduce方法會遍歷數(shù)組的每個(gè)元素,并將它們累積到一個(gè)新數(shù)組中。在這個(gè)例子中,我們檢查累積器是否包含當(dāng)前值,如果不包含,則將其添加到累積器中。
這些方法各有優(yōu)缺點(diǎn),選擇哪種方法取決于你的需求和喜好。