Search This Blog

2023/06/01

How to Remove Duplicate from Object Array:

let obj = [{ name: "sangram", age: 60 }, { name: "sangram", age: 60 }, { name: "sagar", age: 56 }, { name: "sagar", age: 56 }]


//method 1
var noduplicates = []
for (let i = 0; i < obj.length; i++) {
let entry = obj[i]

var index = obj.findIndex((t) => {
return t.name == entry.name && t.age == entry.age
})
if (index == i) {
noduplicates.push(entry)
}
}

console.log(noduplicates)


//more refine method
var nodup = obj.filter((entry, index, self) => {
return index == obj.findIndex((t) => {
return t.name == entry.name && t.age == entry.age
})
})

console.log(nodup)

No comments:

Post a Comment