0

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: enter image description here

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.

Joppe Meijers
  • 301
  • 4
  • 24
  • here's SO question about creating unique arrays https://stackoverflow.com/questions/18773778/create-array-of-unique-objects-by-property – peter Jul 09 '20 at 13:34

2 Answers2

0

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)
    }
}
Çağatay Sel
  • 801
  • 7
  • 14
0

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.

Konstantin
  • 1,390
  • 6
  • 18