首頁常見問題正文

js數(shù)組去重,能用幾種方法實現(xiàn)?

更新時間:2023-06-01 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

  在JavaScript中,有多種方法可以對數(shù)組進行去重操作。針對每一種去重的方法,筆者將給出以下具體的代碼演示:

       1.使用Set數(shù)據(jù)結(jié)構(gòu):

  Set是ES6引入的一種新的數(shù)據(jù)結(jié)構(gòu),它可以存儲唯一的值,因此可以通過將數(shù)組轉(zhuǎn)換為Set來實現(xiàn)去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]

  
       2.使用Array.prototype.filter()方法:

  可以使用filter()方法和indexOf()方法結(jié)合,遍歷數(shù)組并只保留第一個出現(xiàn)的元素。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => {
  return self.indexOf(value) === index;
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]

  

1685587252022_JS數(shù)組去重有幾種方式.jpg

     
      3.使用Array.prototype.reduce()方法:

  可以使用reduce()方法遍歷數(shù)組,并將每個元素添加到結(jié)果數(shù)組中,但只有在結(jié)果數(shù)組中不存在相同的元素時才添加。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, value) => {
  if (!acc.includes(value)) {
    acc.push(value);
  }
  return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]

  
       4.使用for循環(huán)和臨時對象:

  使用for循環(huán)遍歷數(shù)組,將數(shù)組中的元素作為對象的屬性,只保留第一次出現(xiàn)的元素。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [];
const tempObj = {};
for (let i = 0; i < array.length; i++) {
  if (!tempObj[array[i]]) {
    tempObj[array[i]] = true;
    uniqueArray.push(array[i]);
  }
}
console.log(uniqueArray); // [1, 2, 3, 4, 5]

  以上就是常見的JS去重方法,根據(jù)具體情況選擇適合的方法來實現(xiàn)數(shù)組去重。

分享到:
在線咨詢 我要報名
和我們在線交談!