溫馨提示×

JavaScript數(shù)組去重怎樣高效

小樊
81
2024-10-25 16:28:42
欄目: 編程語言

在JavaScript中,可以使用以下幾種方法高效地對數(shù)組進行去重:

  1. 使用Set
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構造函數(shù),我們可以創(chuàng)建一個只包含唯一值的集合。然后,我們使用Array.from()方法將Set對象轉換回數(shù)組。

  1. 使用filter()方法
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)的測試的所有元素。在這個例子中,我們傳遞一個箭頭函數(shù)作為參數(shù),該函數(shù)檢查當前元素在原數(shù)組中的第一個出現(xiàn)的索引是否等于當前索引。如果相等,說明這是第一次出現(xiàn)該元素,將其保留在新數(shù)組中。

  1. 使用reduce()方法
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ù)組的每個元素,并將值累積到一個單一的輸出值中。在這個例子中,我們將累積器初始化為一個空數(shù)組。對于每個元素,我們檢查它是否已經包含在累積器數(shù)組中。如果尚未包含,我們將其添加到累積器數(shù)組中。最后,reduce()方法返回累積器數(shù)組,其中包含了去重后的元素。

0