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

javascriptweb developmentobject oriented programming更新于 2025/9/28 19:24:17

我们需要编写一个函数,从数组中删除重复的对象并返回一个新对象。如果两个对象具有相同数量的键、相同的键和每个键相同的值,则将一个对象视为另一个对象的重复项。

让我们为此编写代码 −

我们将使用映射以字符串形式存储不同的对象,一旦我们看到重复的键,我们就忽略它,否则我们将对象推送到新数组中 −

示例

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

相关文章


有用资源