3

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!

3
  • 4
    What is your question? :) Commented Mar 27, 2019 at 9:38
  • How to stop the duplicate entries @Webber Commented Mar 27, 2019 at 9:40
  • @RobbyCornelissen yeah just saw that Commented Mar 27, 2019 at 9:41

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.