Attempting to remove an object from an array if the age property matches using the provided 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}
However, making a slight alteration by only pushing the age property to the array yields a correct result:
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.
The conditions in both versions of the code are identical. Strangely, the first version adds 3 items to the empty array while the second version successfully adds only 2 items. How can this inconsistency be explained?