溫馨提示×

JavaScript數(shù)組去重怎樣快速

小樊
81
2024-10-25 16:30:43
欄目: 編程語言

在JavaScript中,可以使用以下幾種方法來快速去除數(shù)組中的重復(fù)元素:

  1. 使用Set對象(推薦)
function uniqueArray(arr) {
  return Array.from(new Set(arr));
}

const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(arrayWithDuplicates);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]

Set對象允許你存儲唯一的值,所以我們可以將數(shù)組傳遞給Set構(gòu)造函數(shù),然后再使用Array.from()方法將Set對象轉(zhuǎn)換回數(shù)組。

  1. 使用filter()方法
function uniqueArray(arr) {
  return arr.filter((item, index) => {
    return arr.indexOf(item) === index;
  });
}

const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(arrayWithDuplicates);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]

filter()方法會創(chuàng)建一個新數(shù)組,其中包含通過所提供函數(shù)實現(xiàn)的測試的所有元素。在這個例子中,我們檢查當前元素的索引是否與其在數(shù)組中第一次出現(xiàn)的索引相同,如果不同,則說明它是唯一的。

  1. 使用reduce()方法
function uniqueArray(arr) {
  return arr.reduce((accumulator, currentValue) => {
    if (!accumulator.includes(currentValue)) {
      accumulator.push(currentValue);
    }
    return accumulator;
  }, []);
}

const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(arrayWithDuplicates);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]

reduce()方法會迭代數(shù)組的每個元素,并將它們累積到一個新數(shù)組中。在這個例子中,我們檢查累積器是否包含當前值,如果不包含,則將其添加到累積器中。

雖然這些方法都可以實現(xiàn)數(shù)組去重的目的,但推薦使用Set對象的方法,因為它的性能更好,而且代碼更簡潔。

0