Indraraj26
Indraraj26

Reputation: 1966

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]

Upvotes: 0

Views: 1352

Answers (2)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

+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));
})

Upvotes: 0

Picci
Picci

Reputation: 17752

You can try this

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

The key here is

  • mergeMap is actually a flatten Observable-like objects (actually mergeMap was formerly known as flatMap)
  • an Array is treated as an Observable since it actually can represent a stream of data, which is what an Observable is

Upvotes: 1

Related Questions