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