在 JavaScript 中从数组中删除重复对象

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 7:40:17

假设我们有一个像这样的对象数组 −

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' } ]

相关文章


有用资源