在JavaScript中,可以使用以下幾種方法來對數(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]
Set對象允許你存儲唯一的值,無論這些值是原始值還是對象引用。通過將數(shù)組傳遞給Set構(gòu)造函數(shù),可以創(chuàng)建一個包含數(shù)組中所有唯一值的新集合。然后,可以使用Array.from()方法將Set對象轉(zhuǎn)換回數(shù)組。
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]
filter()方法創(chuàng)建一個新數(shù)組,其中包含通過所提供函數(shù)實現(xiàn)的測試的所有元素。在這個例子中,我們使用filter()方法遍歷數(shù)組,并檢查每個元素的索引是否與其在數(shù)組中第一次出現(xiàn)的索引相同。如果相同,則說明該元素是唯一的,將其保留在新數(shù)組中。
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]
reduce()方法對累加器和數(shù)組中的每個元素(從左到右)應(yīng)用一個函數(shù),將其減少為單個值。在這個例子中,我們使用reduce()方法遍歷數(shù)組,并將不重復(fù)的元素添加到累加器數(shù)組中。如果當(dāng)前值已經(jīng)包含在累加器數(shù)組中,則不會將其添加。最后,reduce()方法返回包含所有唯一值的新數(shù)組。