Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for duplicate values in array of objects in angular2

Tags:

angular

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')
            } 
           });
like image 270
coder12349 Avatar asked Feb 24 '26 08:02

coder12349


2 Answers

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);
 }
like image 189
Chatar Singh Avatar answered Feb 27 '26 03:02

Chatar Singh


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')
}
like image 38
Krishna Rathore Avatar answered Feb 27 '26 02:02

Krishna Rathore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!