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

回答編集履歴

2

テキスト追加

2020/05/20 00:10

投稿

jun68ykt
jun68ykt

スコア9058

answer CHANGED
@@ -44,4 +44,61 @@
44
44
  ```
45
45
  - **動作確認用サンプル:** [https://codepen.io/jun68ykt/pen/wvKQLYK?editors=0012](https://codepen.io/jun68ykt/pen/wvKQLYK?editors=0012)
46
46
 
47
- 以上、参考になれば幸いです。
47
+ 以上、参考になれば幸いです。
48
+
49
+ ### 追記
50
+
51
+ 別案です。同じ sensor_group_id ごとのグルーピングを行うために、lodash の [_.groupBy](https://lodash.com/docs/#groupBy) を使います。
52
+
53
+ ```javascript
54
+ const data = {
55
+ group: [
56
+ {
57
+ uid: 1001,
58
+ list: [
59
+ { sensor_group_id: 117 },
60
+ { sensor_group_id: 118 }
61
+ ]
62
+ },
63
+ {
64
+ uid: 1002,
65
+ list: [
66
+  { sensor_group_id: 119 },
67
+  ]
68
+ },
69
+ {
70
+ uid: 1003,
71
+ list: [
72
+  { sensor_group_id: 116 },
73
+  { sensor_group_id: 117 },
74
+  ]
75
+ },
76
+ ]
77
+ }
78
+
79
+ const pairs = data.group.map(x =>
80
+ x.list.map(y => [y.sensor_group_id, x.uid])
81
+ ).flat();
82
+
83
+ console.log(pairs);
84
+
85
+ const groups = _(pairs)
86
+ .groupBy(0)
87
+ .mapValues(v => v.map(x => x[1]).sort((x1, x2) => x1 - x2))
88
+ .value();
89
+
90
+ console.log(groups);
91
+
92
+ const result = Object.entries(groups)
93
+ .sort(([x1], [x2]) => x1 - x2)
94
+ .map(([x, y]) => ({
95
+ sensor_group_id: +x,
96
+ list: y
97
+ }));
98
+
99
+ console.log(result);
100
+
101
+
102
+
103
+ ```
104
+ - **動作確認用サンプル:** [https://codepen.io/jun68ykt/pen/RwWEpWb?editors=0012](https://codepen.io/jun68ykt/pen/RwWEpWb?editors=0012)

1

テキスト追加

2020/05/20 00:10

投稿

jun68ykt
jun68ykt

スコア9058

answer CHANGED
@@ -23,9 +23,9 @@
23
23
  上記の `pairs` から以下によって `result` を得ることができます。
24
24
 
25
25
  ```javascript
26
- const result = pairs.reduce((ary, [gid, uid]) => {
26
+ const result = pairs.reduce((ary, [gid, uid], i) => {
27
+ const x = i > 0 ? ary[ary.length - 1] : null;
27
- const x = ary.find(e => e.sensor_group_id === gid);
28
+ if (x && x.sensor_group_id === gid) {
28
- if (x) {
29
29
  x.list.push(uid);
30
30
  } else {
31
31
  ary.push({ sensor_group_id: gid, list: [uid] });
@@ -42,6 +42,6 @@
42
42
  { sensor_group_id: 119, list: [ 1002 ] }
43
43
  ]
44
44
  ```
45
- - **動作確認用サンプル:** [https://codepen.io/jun68ykt/pen/gOaQNWy?editors=0012](https://codepen.io/jun68ykt/pen/gOaQNWy?editors=0012)
45
+ - **動作確認用サンプル:** [https://codepen.io/jun68ykt/pen/wvKQLYK?editors=0012](https://codepen.io/jun68ykt/pen/wvKQLYK?editors=0012)
46
46
 
47
47
  以上、参考になれば幸いです。