I have an array of objects:
const obj = [{
id: 1,
name: 'A'
}, {
id: 1,
name: 'A'
}, {
id: 1,
name: 'A'
}, {
id: 2,
name: 'A'
}, {
id: 2,
name: 'A'
}]
// this method returned me one object with id=1
const filter = obj.reduce((val, index) => {
return index === val.findIndex(v => obj.id === v.id && obj.name === o.name)
})
When I push the button I want to remove one of the duplicate object. For example I have 3 object within an array with ID=1. I want to remove only one object with ID=1 and not two. So the result must be like this:
const obj = [{
id: 1,
name: 'A'
}, {
id: 1,
name: 'A'
}, {
id: 2,
name: 'A'
}, {
id: 2,
name: 'A'
}]
2
Answers
You can achieve this by finding the index of the first object with
id=1
and then usingArray.prototype.splice()
to remove it:Here is code that will take any number of objects and leave a maximum of two duplicates