File tree Expand file tree Collapse file tree 3 files changed +33
-2
lines changed
solution/2700-2799/2722.Join Two Arrays by ID Expand file tree Collapse file tree 3 files changed +33
-2
lines changed Original file line number Diff line number Diff line change @@ -95,7 +95,17 @@ arr2 = [
95
95
<!-- 这里可写当前语言的特殊实现逻辑 -->
96
96
97
97
``` ts
98
-
98
+ function join(arr1 : any [], arr2 : any []): any [] {
99
+ const d = new Map (arr1 .map (x => [x .id , x ]));
100
+ arr2 .forEach (x => {
101
+ if (d .has (x .id )) {
102
+ d .set (x .id , { ... d .get (x .id ), ... x });
103
+ } else {
104
+ d .set (x .id , x );
105
+ }
106
+ });
107
+ return [... d .values ()].sort ((a , b ) => a .id - b .id );
108
+ }
99
109
```
100
110
101
111
<!-- tabs:end -->
Original file line number Diff line number Diff line change @@ -89,7 +89,17 @@ arr2 = [
89
89
### ** TypeScript**
90
90
91
91
``` ts
92
-
92
+ function join(arr1 : any [], arr2 : any []): any [] {
93
+ const d = new Map (arr1 .map (x => [x .id , x ]));
94
+ arr2 .forEach (x => {
95
+ if (d .has (x .id )) {
96
+ d .set (x .id , { ... d .get (x .id ), ... x });
97
+ } else {
98
+ d .set (x .id , x );
99
+ }
100
+ });
101
+ return [... d .values ()].sort ((a , b ) => a .id - b .id );
102
+ }
93
103
```
94
104
95
105
<!-- tabs:end -->
Original file line number Diff line number Diff line change
1
+ function join ( arr1 : any [ ] , arr2 : any [ ] ) : any [ ] {
2
+ const d = new Map ( arr1 . map ( x => [ x . id , x ] ) ) ;
3
+ arr2 . forEach ( x => {
4
+ if ( d . has ( x . id ) ) {
5
+ d . set ( x . id , { ...d . get ( x . id ) , ...x } ) ;
6
+ } else {
7
+ d . set ( x . id , x ) ;
8
+ }
9
+ } ) ;
10
+ return [ ...d . values ( ) ] . sort ( ( a , b ) => a . id - b . id ) ;
11
+ }
You can’t perform that action at this time.
0 commit comments