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

回答編集履歴

2

コードを整理してみた

2017/07/15 07:41

投稿

Lhankor_Mhy
Lhankor_Mhy

スコア37577

answer CHANGED
@@ -25,7 +25,7 @@
25
25
  ];
26
26
 
27
27
  var before_clone = before.slice();
28
- var children_temp = new Array(before.length);
28
+ var children_temp = new Array(before.length+1);
29
29
 
30
30
  before = before.filter(function (el, _, before) {
31
31
  if (el.parent !== 0) {
@@ -53,4 +53,32 @@
53
53
  /*
54
54
  [{id:1, parent:0, children:[{id:3, parent:1, children:[{id:5, parent:3}]}]}, {id:2, parent:0, children:[{id:4, parent:2}]}]
55
55
  */
56
+ ```
57
+  
58
+  
59
+ ##### コードを整理してみた
60
+ 短くなった。
61
+ ```javascript
62
+ var children_temp = Array.apply( null, Array( before.length + 1 ) ).map( function(){return []} ); // Array.prototype.fill()代替
63
+
64
+ before.forEach(function ( el, _, _ ) {
65
+ children_temp[el.parent].push(el);
66
+ });
67
+
68
+ before = before.filter(function ( el, _, _ ) {
69
+ if ( children_temp[el.id].length ) el.children = children_temp[el.id];
70
+ return ( el.parent === 0 );
71
+ });
72
+ ```
73
+
74
+ 空の配列をchildrenに許容してくれるなら、ワンライナーいける。
75
+ ```javascript
76
+ before = before.filter(
77
+ function ( el, _, _ ) {
78
+ this[el.parent].push(el);
79
+ el.children = this[el.id];
80
+ return ( el.parent === 0 );
81
+ },
82
+ Array.apply( null, Array( before.length + 1 ) ).map( function(){return []} )
83
+ );
56
84
  ```

1

整形

2017/07/15 07:41

投稿

Lhankor_Mhy
Lhankor_Mhy

スコア37577

answer CHANGED
@@ -31,8 +31,7 @@
31
31
  if (el.parent !== 0) {
32
32
  //ルート要素じゃなければ参照に追加しフィルタ
33
33
  var target = children_temp[el.parent];
34
- if (target === undefined) children_temp[el.parent] = target = [
34
+ if (target === undefined) children_temp[el.parent] = target = [];
35
- ];
36
35
  target.push(el);
37
36
  return false;
38
37
  } else {