satya satya - 2 months ago 10
Javascript Question

Can not remove the duplicate value from array using Javascript

I am unable to remove the duplicate value from array using Javascript.



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

var outputList = [];

for (var i = 0; i < arr.length; i++) {
if (outputList.indexOf(arr[i].image) == -1) {
var data = {
image: arr[i].image,
gallery_image: arr[i].gallery_image
};
outputList.push(data);
}
}

console.log(outputList)





Here i can not delete the data properly. Please help me.

Answer

Instead of indexOf() method you should use some(). From MDN:

The some() method tests whether some element in the array passes the test implemented by the provided function.

if (!outputList.some(x => x.image === arr[i].image))

Working demo

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

var outputList=[];

for(var i = 0; i < arr.length; i++){
   if (!outputList.some(x => x.image === arr[i].image)){
   var data={ image: arr[i].image,gallery_image:arr[i].gallery_image };
   outputList.push(data);
   }
}

console.log(outputList)