

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove duplicates from a array of objects JavaScript
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' } ]
- Related Questions & Answers
- The best way to remove duplicates from an array of objects in JavaScript?
- Remove duplicates from array with URL values in JavaScript
- Remove array duplicates by property - JavaScript
- Counting duplicates and aggregating array of objects in JavaScript
- Remove Duplicates from Sorted Array in Python
- Merge and remove duplicates in JavaScript Array
- Remove duplicates from an array keeping its length same in JavaScript
- Remove Duplicates from Sorted Array II in C++
- Remove duplicates and map an array in JavaScript
- Removing duplicates from a sorted array of literals in JavaScript
- Remove duplicates from a List in C#
- Java Program to Remove Duplicates from an Array List
- Write a program in C++ to remove duplicates from a given array of prime numbers
- Search from an array of objects via array of string to get array of objects in JavaScript
- Remove all duplicates from a given string in Python
Advertisements