Reputation: 425
I am trying to add Objects as elements into an array. I am able to restrict the first already added element but subsequent entries are being duplicated.
Here' the code:
onAddButtonPress(data, id, name){
const items = this.props.items;
if(items.length >= 1){
items.forEach(i=>
{
if(i.id !== id){
const arr = data.map(i=>{
return i.name
})
this.props.addToShopList({id:id, arr:arr, name:name})
}
}
)
}
else{
const arr = data.map(i=>{
return i.name
})
this.props.addToShopList({id:id, arr:arr, name:name})
}
}
How to stop this duplicate entries? Please suggest. Thanks!
Upvotes: 3
Views: 190
Reputation: 97152
You're adding to the list from inside the loop, which doesn't seem right. There are also a number of unneeded checks and duplicated code.
This should be sufficient, using Array.prototype.some()
:
onAddButtonPress(data, id, name) {
const items = this.props.items;
if (!items.some(i => i.id === id)) {
const arr = data.map(({name}) => name);
this.props.addToShopList({id, arr, name});
}
}
Complete class example:
class Test {
constructor() {
this.props = {
items: [],
addToShopList: (item) => this.props.items.push(item)
};
}
onAddButtonPress(data, id, name) {
const items = this.props.items;
if (!items.some(i => i.id === id)) {
const arr = data.map(({name}) => name);
this.props.addToShopList({id, arr, name});
}
}
}
const test = new Test();
test.onAddButtonPress([], 1, "One");
test.onAddButtonPress([], 2, "Two");
test.onAddButtonPress([], 2, "Two");
console.log(test.props.items);
Upvotes: 3