從 JavaScript 陣列中移除重複物件


假設我們有一個這樣的物件陣列——

const arr = [
   {"title": "Assistant"},
   {"month": "July"},
   {"event": "Holiday"},
   {"title": "Assistant"}
];

我們需要編寫一個 JavaScript 函式,它會獲取一個這樣的陣列。然後,我們的函式應該返回一個新陣列,其中包含原始陣列中的所有物件,但沒有重複的物件。

示例

以下為程式碼——

const arr = [
   {"title": "Assistant"},
   {"month": "July"},
   {"event": "Holiday"},
   {"title": "Assistant"}
];
const removeDuplicate = arr => {
   const map = {};
   for(let i = 0; i < arr.length; ){
      const str = JSON.stringify(arr[i]);
      if(map.hasOwnProperty(str)){
         arr.splice(i, 1);
         continue;
      };
      map[str] = true;
      i++;
   };
};
removeDuplicate(arr);
console.log(arr);

輸出

控制檯中的輸出——

[ { title: 'Assistant' }, { month: 'July' }, { event: 'Holiday' } ]

更新於: 12-Oct-2020

251 次瀏覽

啟動你的 職業生涯

完成此課程,獲得認證

開始學習
廣告
© . All rights reserved.