why groupBy from rxjs in angular is not working?

When i map from my object and then aply groupBy it doenst group. Let me show.

this.accountService.list(acc1).pipe(
      map((ac :any) => ac.list),
      groupBy(x => x.currency),
      mergeMap(group =>  group.pipe(toArray()))
    ).subscribe(data => {
      data.forEach((l: AccountDto[]) => { //para cada lista de moneda
        if (l.length != 0) {
          console.log("cuenta: " + l[0].currency);
          l.forEach(x => console.log(x));
        }
      })
    }, error => {
      console.log(error);
    });

Here the results in console:

cuenta: Bs.
summary.component.ts:45 {numAccount: "002051210266", currency: "Bs.", amount: "2,000.06", typeAccount: "CA", state: "NO", …}
summary.component.ts:45 {numAccount: "002051210278", currency: "Bs.", amount: "745.00", typeAccount: "CA", state: "NO", …}
summary.component.ts:45 {numAccount: "002052210287", currency: "$us", amount: "800.00", typeAccount: "CA", state: "NO", …}

There are two currency = 'Bs.' and one currency = '$us' but the three are in the same array.

Feel free to make questions. (Im latino please ignore my English sintaxis)

EDIT1: This is my expected output:

cuenta: Bs.
summary.component.ts:45 {numAccount: "002051210266", currency: "Bs.", amount: "2,000.06", typeAccount: "CA", state: "NO", …}
summary.component.ts:45 {numAccount: "002051210278", currency: "Bs.", amount: "745.00", typeAccount: "CA", state: "NO", …}
cuenta: $us.
summary.component.ts:45 {numAccount: "002052210287", currency: "$us", amount: "800.00", typeAccount: "CA", state: "NO", …}

Upvotes: 1

Views: 498

Answers (2)

Siva Rm K
Siva Rm K

Reputation: 294

instead map use mergeMap in first line

 this.accountService.list(acc1).pipe(
          mergeMap((ac :any) => ac.list),
          groupBy(x => x.currency),
          mergeMap(group =>  group.pipe(toArray()))
        ).subscribe(data => {
          data.forEach((l: AccountDto[]) => { //para cada lista de moneda
            if (l.length != 0) {
              console.log("cuenta: " + l[0].currency);
              l.forEach(x => console.log(x));
            }
          })
        }, error => {
          console.log(error);
        });

Upvotes: 0

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

That is because groupBy groups emittions of the stream. Your only emission is the array, not the elements of the array. You simply need to stream the elements of the array. You can use concatAll for that.

const data = {
  list: [
    {numAccount: "002051210266", currency: "Bs.", amount: "2,000.06", typeAccount: "CA", state: "NO"},
    {numAccount: "002051210278", currency: "Bs.", amount: "745.00", typeAccount: "CA", state: "NO"},
    {numAccount: "002052210287", currency: "$us", amount: "800.00", typeAccount: "CA", state: "NO"},
  ]
}

of(data).pipe(
  map(ac => ac.list),
  concatAll(), // HERE
  groupBy(x => x.currency),
  mergeMap(group =>  group.pipe(toArray()))
).subscribe(console.log);

Upvotes: 1

Related Questions