简体   繁体   中英

exclude already existing items from array in React

I am facing a challenge. I have 2 tables in firebase that I need to merge into 1 array. The only thing is that items are the same, they have to be removed from the array. So if an item already exists in an array, it should no longer be added to the array. So at the moment I get to see the items twice. Is there a possibility to prevent this? My function looks like this:

  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],
          }));
          });
      })
  }

My database looks like this: 在此处输入图像描述

So you see that these items have the same key. These are also identical to each other. However, if 1 has already been added, this is sufficient, now they are both added.

Here is how you can merge an array into another without duplicates.

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

You could use a Set , which doesn't let you add duplicate values. So the easiest you could achieve is something like:

const yourFinalArray = [...new Set([...arr1, ...arr2]);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM