
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Duplicate Values from Array in JavaScript
Suppose, we have some data regarding some images in an array like this −
const arr = [{ 'image': "jv2bcutaxrms4i_img.png", 'gallery_image': true }, { 'image': "abs.png", 'gallery_image': true }, { 'image': "acd.png", 'gallery_image': false }, { 'image': "jv2bcutaxrms4i_img.png", 'gallery_image': true }, { 'image': "abs.png", 'gallery_image': true }, { 'image': "acd.png", 'gallery_image': false }];
We are required to write a JavaScript function that takes in one such array.
Our function should remove the objects from the array that have duplicate values for the 'image' property.
Example
The code for this will be −
const arr = [{ 'image': "jv2bcutaxrms4i_img.png", 'gallery_image': true }, { 'image': "abs.png", 'gallery_image': true }, { 'image': "acd.png", 'gallery_image': false }, { 'image': "jv2bcutaxrms4i_img.png", 'gallery_image': true }, { 'image': "abs.png", 'gallery_image': true }, { 'image': "acd.png", 'gallery_image': false }]; const buildUnique = (arr = []) => { const unique = []; arr.forEach(obj => { let found = false; unique.forEach(uniqueObj => { if(uniqueObj.image === obj.image) { found = true; }; }); if(!found){ unique.push(obj); }; }); return unique; }; console.log(buildUnique(arr));
Output
And the output in the console will be −
[ { image: 'jv2bcutaxrms4i_img.png', gallery_image: true }, { image: 'abs.png', gallery_image: true }, { image: 'acd.png', gallery_image: false } ]
Advertisements