限制JavaScript中数组的重复条目

3

我正在尝试将对象作为元素添加到数组中。我能够限制已添加的第一个元素,但是后续的条目会被重复添加。

这是代码:

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

}

如何停止重复记录? 请给出建议。谢谢!

4
你有什么问题? :) - Webber
如何停止@Webber中的重复条目 - Saumay Paul
@RobbyCornelissen 是的,我刚看到了。 - Vladimir Bogomolov
1个回答

3
你正在循环内部添加到列表中,这似乎不正确。还有许多不必要的检查和重复的代码。
这应该足够了,使用 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});
  }
}

完整的类示例:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接