從物件陣列中刪除重複項JavaScript


我們需要編寫一個函式從陣列中刪除重複物件並返回一個新的陣列。如果兩個物件的鍵數相同、鍵相同且每個鍵的值相同,則認為一個物件是另一個物件的重複。

讓我們寫出如下程式碼:

我們將使用一個對映以字串形式儲存不同的物件,一旦看到重複的鍵,我們就忽略它,否則將物件推入新陣列中:

示例

const arr = [
   {
      "timestamp": 564328370007,
      "message": "It will rain today"
   },
   {
      "timestamp": 164328302520,
      "message": "will it rain today"
   },
   {
      "timestamp": 564328370007,
      "message": "It will rain today"
   },
   {
      "timestamp": 564328370007,
      "message": "It will rain today"
   }
   ];
   const map = {};
   const newArray = [];
   arr.forEach(el => {
      if(!map[JSON.stringify(el)]){
         map[JSON.stringify(el)] = true;
         newArray.push(el);
   }
});
console.log(newArray);

輸出

控制檯中的輸出為:

[
   { timestamp: 564328370007, message: 'It will rain today' },
   { timestamp: 164328302520, message: 'will it rain today' }
]

更新時間:2020年8月20日

581次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告