JavaScript數(shù)組去重如何確保

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

在JavaScript中,確保數(shù)組去重的同時(shí)保持原始順序,可以使用以下方法:

function uniqueArray(arr) {
  const result = [];
  const map = new Map();

  for (const item of arr) {
    if (!map.has(item)) {
      map.set(item, true);
      result.push(item);
    }
  }

  return result;
}

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

這個(gè)方法使用了一個(gè)Map對(duì)象來跟蹤已經(jīng)遇到的元素。當(dāng)遍歷數(shù)組時(shí),如果元素不在Map中,就將其添加到結(jié)果數(shù)組和Map中。這樣可以確保結(jié)果數(shù)組中沒有重復(fù)的元素,同時(shí)保持了原始順序。

0