0

I tried to do infinite scroll in angular with firebase data. You can see this referance.There is a kind of simple pagination when user scrolled down. In this referance, a kind of "once listener" is applied with

    this.movieService
    .getMovies(this.batch+1, this.lastKey)
    .do(movies => {
      /// set the lastKey in preparation for next query
      this.lastKey = _.last(movies)['$key']
      const newMovies = _.slice(movies, 0, this.batch)
      /// Get current movies in BehaviorSubject
      const currentMovies = this.movies.getValue()
      /// If data is identical, stop making queries
      if (this.lastKey == _.last(newMovies)['$key']) {
        this.finished = true
      }
      /// Concatenate new movies to current movies
      this.movies.next( _.concat(currentMovies, newMovies) )
    })
    .take(1)
    .subscribe()

But im trying to do real time application and when user called an action, it is not responding some new data. Because of that, i remove take(1). When I do this, there will be some duplicate data because listeners will be triggered and when listener triggered it will concatenate two arrays.

Our arrays are object arrays and I want to update first array when dublicate with second array. For example first array is like,

[{ $key :"1",firstname:"Ben",lastname:"Fried",point:1 },
 { $key :"2",firstname:"Carlo",lastname:"Strozzi",point:5},
 { $key :"3",firstname:"Jim",lastname:"DuBois",point:8}]

and second array is like,

[{ $key :"2",firstname:"Carlo",lastname:"Strozzi",point:3}
 { $key :"4",firstname:"Larry",lastname:"Page",point:10 }]

Our concatenated array has to be

[{ $key :"1",firstname:"Ben",lastname:"Fried",point:1 },
 { $key :"2",firstname:"Carlo",lastname:"Strozzi",point:3},
 { $key :"3",firstname:"Jim",lastname:"DuBois",point:8},
 { $key :"4",firstname:"Larry",lastname:"Page",point:10 }]

Note : $key are unique.

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
İbrahim Dolapci
  • 283
  • 1
  • 3
  • 10

1 Answers1

0

If the order is not important( or you can sort on your side after merging ), you can create an object which indexes the documents by $key, and overwrite existing $keys if that $key alread exists as a key in the object.

Here is a sample snippet:

let resultObj = {};

let array1 = [
  { $key: '1', firstname: 'Ben', lastname: 'Fried', point: 1 },
  { $key: '2', firstname: 'Carlo', lastname: 'Strozzi', point: 5 },
  { $key: '3', firstname: 'Jim', lastname: 'DuBois', point: 8 },
];

let array2 = [
  { $key: '2', firstname: 'Carlo', lastname: 'Strozzi', point: 3 },
  { $key: '4', firstname: 'Larry', lastname: 'Page', point: 10 },
];

for (let i = 0; i < array1.length; i++) {
  resultObj[array1[i].$key] = array1[i];
}

for (let i = 0; i < array2.length; i++) {
  resultObj[array2[i].$key] = array2[i];
}

console.log(Object.values(resultObj));
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92