I have a requirment where i need to check for only duplicate description in array of objects. Below is the object example.
traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 10},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
{ description: 'Adult', Amount: 105},
];
In the above array traveler there are objects with duplicate description, so how to check only for duplicate description throught out the array and display a message.
I am using reduce method,below is the code. but the control is not going inside the if loop
Am i going wrong somewhere?
var res = traveler.reduce((acc, obj)=>{
var existItem = acc.find(item => item.description === obj.description);
if(existItem){
return this.toaster.pop('info', 'Insertion unsuccessful', 'Duplicate answer found')
}
});
Try this.
reduce(){
let res=[];
this.traveler.map(function(item){
var existItem = res.find(x=>x.description==item.description);
if(existItem)
console.log("item already exist");
else
res.push(item);
});
console.log(res);
}
remove reduce and use only filter.
let existItem = traveler.filter(item => item.description === obj.description);
if (existItem.length > 1) {
return this.toaster.pop('info', 'Insertion unsuccessful', 'Duplicate answer found')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With