@@ -31,9 +31,21 @@ export function groupsByUserId(organizationId: string) {
31
31
return {
32
32
...groups ( organizationId ) ,
33
33
select : ( allGroups ) => {
34
- const userIdMapper = new Map < string , Group [ ] > ( ) ;
34
+ // Sorting here means that nothing has to be sorted for the individual
35
+ // user arrays later
36
+ const sorted = [ ...allGroups ] . sort ( ( g1 , g2 ) => {
37
+ const key =
38
+ g1 . display_name && g2 . display_name ? "display_name" : "name" ;
35
39
36
- for ( const group of allGroups ) {
40
+ if ( g1 [ key ] === g2 [ key ] ) {
41
+ return 0 ;
42
+ }
43
+
44
+ return g1 [ key ] < g2 [ key ] ? - 1 : 1 ;
45
+ } ) ;
46
+
47
+ const userIdMapper = new Map < string , Group [ ] > ( ) ;
48
+ for ( const group of sorted ) {
37
49
for ( const user of group . members ) {
38
50
let groupsForUser = userIdMapper . get ( user . id ) ;
39
51
if ( groupsForUser === undefined ) {
@@ -45,23 +57,6 @@ export function groupsByUserId(organizationId: string) {
45
57
}
46
58
}
47
59
48
- // Defined outside the loop because it can be reused by all group arrays,
49
- // and doesn't need to be rebuilt from scratch on each iteration
50
- const orderGroupsByName = ( g1 : Group , g2 : Group ) => {
51
- const key =
52
- g1 . display_name && g2 . display_name ? "display_name" : "name" ;
53
-
54
- if ( g1 [ key ] === g2 [ key ] ) {
55
- return 0 ;
56
- }
57
-
58
- return g1 [ key ] < g2 [ key ] ? - 1 : 1 ;
59
- } ;
60
-
61
- for ( const groupsList of userIdMapper . values ( ) ) {
62
- groupsList . sort ( orderGroupsByName ) ;
63
- }
64
-
65
60
return userIdMapper as GroupsByUserId ;
66
61
} ,
67
62
} satisfies UseQueryOptions < Group [ ] , unknown , GroupsByUserId > ;
0 commit comments