0

I’m working in an angular 6 application. I have a function that returns an observable of an array of observables, which in turn are observables of arrays.

The results might look something like this:

[
  [],
  [],
  [object, object],
  [],
  [object],
  [],
  [object, object, object],
  []
]

As you can see, it’s an array of arrays and some arrays might be empty.

I’d like to list each object in each inner array on the page as follows:

<div *ngFor="let watcher of InvitationService.getInvitations() | async">
  <div *ngFor="let invitation of watcher">
    {{ invitation | json }}
  </div>
</div>

And getInvitations() looks like this:

getInvitations() {
  const groupedInvitations$: Observable<any>[] = [];
  groups.forEach(group => {
    const groupInvites$ = this._firestoreService.collection(`GroupInvitations/${group.groupID}/Invites`);
    groupedInvitations$.push(groupInvites$);
  });
  Return Observable.combineLatest(groupedInvitations$);
}

What I’d like to do is remove the empty arrays from the results returned from combineLatest(…) and flatten the rest into a single one dimensional array.

I understand one can do this by piping through map(…) or flatMap(…) or things like that. But I’ve been trying things like that and nothing’s been working.

For example, I’ve tried this:

Return Observable.combineLatest(groupedInvitations$).pipe(
  map(item => {
    console.log(item);
  });
);

But nothing gets logged to the console.

How can I flatten the array and remove empty arrays? Thanks.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Gibran Shah
  • 871
  • 3
  • 15
  • 34
  • I am not sure if map or flatMap/mergeMap will give you what you are after.. Perhaps this link might help: https://stackoverflow.com/questions/33471526/why-do-we-need-to-use-flatmap – JGFMK Feb 15 '19 at 19:18

2 Answers2

1

Try using a filter first to remove the empty arrays and the use combineLatest to put them all together.

combineLatest(
    groupedInvitations$.pipe(
        filter(item => item.length > 0)
    )
).pipe(
    tap(item => { // Should be an array of arrays
        console.log(item);
    });
);
Ben
  • 960
  • 8
  • 17
0

as I see it you can put an if condition before this line groupedInvitations$.push(groupInvites$); to check if the array length is greater than zero if yes add it to the returned array if not go to the next one

hope that helps

  • Hi Faisal! Welcome here. What are you trying to ask? And what language is this? PHP? – StuiterSlurf Feb 15 '19 at 19:24
  • Hi Faisal. The problem with checking groupedInvitations$ is that it's an observable, not the resulting array. It doesn't know, at that point, what the array will contain. – Gibran Shah Feb 15 '19 at 19:47