Remove duplicates from a array of objects JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that removes duplicate objects from an array and returns a new one. Consider one object the duplicate of other if they both have same number of keys, same keys and same value for each key.

Let’s write the code for this −

We will use a map to store distinct objects in stringified form and once we see a duplicate key we omit it otherwise we push the object into the new array −

Example

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);

Output

The output in the console will be −

[
   { timestamp: 564328370007, message: 'It will rain today' },
   { timestamp: 164328302520, message: 'will it rain today' }
]
raja
Published on 20-Aug-2020 09:44:58
Advertisements