Created
December 14, 2022 18:11
-
-
Save Stradivario/e42b35187a21d7a208deb3c31b373d6e to your computer and use it in GitHub Desktop.
Example how we can sort out array of users by age with multiple emissions process them and change to appropriate structure and from multiple emissions to a single using combineAll()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { from, of, zip } from 'rxjs'; | |
import { combineAll, groupBy, map, mergeMap, toArray } from 'rxjs/operators'; | |
const people = [ | |
{ id: 1, name: 'Sue', age: 25 }, | |
{ id: 2, name: 'Joe', age: 30 }, | |
{ id: 3, name: 'Frank', age: 25 }, | |
{ id: 4, name: 'Sarah', age: 35 } | |
]; | |
from(people) | |
.pipe( | |
groupBy(person => person.age), | |
mergeMap(group => zip(of(group.key), group.pipe(toArray()))), | |
map(([age, users]) => of({ age, users })), | |
combineAll() | |
) | |
.subscribe((data) => console.log(JSON.stringify(data, null, 2))); | |
/* | |
[ | |
{ | |
"age": 25, | |
"users": [ | |
{ | |
"name": "Sue", | |
"age": 25 | |
}, | |
{ | |
"name": "Frank", | |
"age": 25 | |
} | |
] | |
}, | |
{ | |
"age": 30, | |
"users": [ | |
{ | |
"name": "Joe", | |
"age": 30 | |
} | |
] | |
}, | |
{ | |
"age": 35, | |
"users": [ | |
{ | |
"name": "Sarah", | |
"age": 35 | |
} | |
] | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment