lundi 29 mars 2021

JavaScript Object Array: Removing objects with duplicate properties. same conditions have different output

I am trying to remove an object from an array if the age property matches using the below codes.

 var state= [
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}
  ]
  
  
 let a= [...state];
 var ids=[]

 var ar = a.filter(function(o) {
    
        if (ids.indexOf(o.age) !== -1){
        return false;
        }
        
        else if(ids.indexOf(o.age) === -1){
        ids.push(o);
        return true;}
})
console.log(ids)

    // OUTPUT: (NOT working fine)
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}

But if I edit the code by pushing only one property in the array, it is working fine:

 var state= [
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}
  ]
  
  
 let a= [...state];
 var ids=[]

 var ar = a.filter(function(o) {
    
        if (ids.indexOf(o.age) !== -1){
        return false;
        }
        
        else if(ids.indexOf(o.age) === -1){
        ids.push(o.age); // Here i have edited the code by pushing only age property to the array
        return true;}
})
console.log(ids)

OUTPUT : [23, 25] // Only two items were added.

There is no difference in the Conditions but in the first code's output 3 items were added in the empty array while in the second code only 2 items get added. How is this possible?

Aucun commentaire:

Enregistrer un commentaire