teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

reduceを使った例を追記

2021/07/09 14:23

投稿

taku-hu
taku-hu

スコア178

answer CHANGED
@@ -1,5 +1,7 @@
1
1
  追記に関して、もっと簡潔に書きたいなら、
2
2
 
3
+ `map`を使って
4
+
3
5
  ```javascript
4
6
  const mergedData = tempRowData.map(oldData => {
5
7
  const newData = draggedRowData.find(({ id }) => oldData.id === id)
@@ -7,10 +9,25 @@
7
9
  }).sort((current, next) => current.order > next.order ? 1 : -1)
8
10
  ```
9
11
 
10
- 読みにくいですが、一行で書きたいなら
12
+ 読みにくいですが、`return`を省略して一行で書きたいなら
11
13
 
12
14
  ```javascript
13
15
  const mergedData = tempRowData.map(oldData => draggedRowData.find(({ id }) => oldData.id === id) ?? oldData).sort((current, next) => current.order - next.order)
14
16
  ```
15
17
 
18
+ `reduce`が使いたいなら
19
+
20
+ ```javascript
21
+ const mergedData = tempRowData.reduce((accumulator, currentValue) => {
22
+ const newData = draggedRowData.find(({ id }) => currentValue.id === id)
23
+ return [...accumulator, newData ?? currentValue]
24
+ }, []).sort((current, next) => current.order > next.order ? 1 : -1)
25
+ ```
26
+
27
+ 同じ要領で一行で書きたいなら
28
+
29
+ ```javascript
30
+ const mergedData = tempRowData.reduce((accumulator, currentValue) => [...accumulator, draggedRowData.find(({ id }) => currentValue.id === id) ?? currentValue], []).sort((current, next) => (current.order - next.order))
31
+ ```
32
+
16
33
  のような感じになるかと思います。

2

修正漏れ箇所の修正

2021/07/09 14:23

投稿

taku-hu
taku-hu

スコア178

answer CHANGED
@@ -10,7 +10,7 @@
10
10
  読みにくいですが、一行で書きたいなら
11
11
 
12
12
  ```javascript
13
- const mergedData = tempRowData.map(oldData => draggedRowData.find(({ id }) => oldData.id === id) || oldData).sort((current, next) => current.order - next.order)
13
+ const mergedData = tempRowData.map(oldData => draggedRowData.find(({ id }) => oldData.id === id) ?? oldData).sort((current, next) => current.order - next.order)
14
14
  ```
15
15
 
16
16
  のような感じになるかと思います。

1

論理和演算子をnull合体演算子に変更

2021/07/09 13:01

投稿

taku-hu
taku-hu

スコア178

answer CHANGED
@@ -3,7 +3,7 @@
3
3
  ```javascript
4
4
  const mergedData = tempRowData.map(oldData => {
5
5
  const newData = draggedRowData.find(({ id }) => oldData.id === id)
6
- return newData || oldData
6
+ return newData ?? oldData
7
7
  }).sort((current, next) => current.order > next.order ? 1 : -1)
8
8
  ```
9
9