Home > front end >  RxJS .pipe() add some items to result array
RxJS .pipe() add some items to result array

Time:06-28

I have a need of adding some static values to the result array that i get from apollo. Here is my code that filters the array and sorts it alphabetically by name, that is why i want to add items in between those 2 pipes:

return this.myService
  .loadCards()
  .pipe(
    map((allCards) =>
      allCards.filter((card) =>
        card.name.toLowerCase().includes(searchQuery.toLowerCase()),
      ),
    ),
  )
  .pipe( // Insert 3 hardcoded objects here)
  .pipe(
    map((allCards) =>
      allCards.sort((a, b) => {
        if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
        if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
        return 0;
      }),
    ),
  );

CodePudding user response:

you can concatenate two arrays like [...arrayone,...arraytwo], so try this (you can move it in an extra map but you don't have to):

return this.myService
   .loadCards()
   .pipe(map((allCards) =>{
      return [
        allCards.filter((card) =>
            card.name.toLowerCase().includes(searchQuery.toLowerCase()),
        ),
        ...["myelement"]
       ];    
    })
).pipe(map((allCards) =>
  allCards.sort((a, b) => {
    if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
    if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
    return 0;
   }),
  ),
);
  • Related