Search code examples
rxjsrxjs5rxjs6rxjs-observablesrxjs-pipeable-operators

how to flatten the nested array in rxjs


I am using forkJoin to subscribe multiple inner observable. How can I flat nested array to single level array.

const x$ = of([1, 2, 3, 4]);
const y$ = of([2, 4]);

x$.pipe(
  switchMap((t) => {
    const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
    return forkJoin(innerArr$);
  })
).subscribe(console.log);

Playground Link: Rxjs stackblitz

Expected Output:

[2,4,4,8,6,12,8,16]

Solution

  • +1 to the answer by @Picci if you want a stream of numbers.

    If you want to wind up with a single array instead, you can flatten the result in the subscription:

    x$.pipe(
      switchMap((t) => {
        const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
        return forkJoin(innerArr$);
      })
    )
    .subscribe((res) => {
      console.log([].concat.apply([], res));
    })