首页 > 解决方案 > 从 React 的数组中排除已经存在的项目

问题描述

我正面临挑战。我在 firebase 中有 2 个表,需要合并到 1 个数组中。唯一的问题是项目是相同的,它们必须从数组中删除。因此,如果某个项目已经存在于数组中,则不应再将其添加到数组中。所以此刻我可以看到这些项目两次。有没有可能阻止这种情况?我的功能如下所示:

  fetchItems(){
    this.setState({
      personalItems:[],
      inactiveItems:[],
       sprintItems:[],
    })
      let ref = Firebase.database().ref('/sprints/1/items/');
      ref.on('value' , snapshot => {
          snapshot.forEach((childSnap) => {
          let state = childSnap.val();
          console.log('firebase output:'+state)
          var newelement = {title: state.title, author: state.author,user: state.user, public: state.public, x: state.x, y: state.y, key: state.key, match: state.match, notes: state.notes, status: state.status};
          this.setState(prevState => ({
            
            personalItems: [...prevState.personalItems, newelement],
          }));
          console.log('firebase'+state.name);
          });
      })
      let refInactive = Firebase.database().ref('/users/'+this.state.user+'/items/');
      refInactive.on('value' , snapshot => {
          snapshot.forEach((childSnap) => {
          let state = childSnap.val();
    

          var newelement = {author: state.author, title: state.postit, status: state.status, key: state.key, user: state.user, match: state.match, x: state.x, y: state.y, public: state.public, notes:state.notes };
          this.setState(prevState => ({
            
            personalItems: [...prevState.personalItems, newelement],
          }));
          });
      })
  }

我的数据库如下所示: 在此处输入图像描述

因此,您会看到这些项目具有相同的密钥。这些也彼此相同。但是,如果已经添加了 1,这就足够了,现在它们都被添加了。

标签: javascriptreactjs

解决方案


以下是如何将一个数组合并到另一个没有重复的数组。

for(arr1Element of array1){
    if(!array2.some(arr2Element => arr2Element.id === arr1Element.id)){
        array2.push(arr1Element)
    }
}

推荐阅读