- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Removing duplicate objects from array in JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"title": "Assistant"}, {"month": "July"}, {"event": "Holiday"}, {"title": "Assistant"} ];
We are required to write a JavaScript function that takes in one such array. Our function should then return a new array that contains all the object from the original array but the duplicate ones.
Example
The code for this will be −
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);
Output
The output in the console −
[ { title: 'Assistant' }, { month: 'July' }, { event: 'Holiday' } ]
Advertisements