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

回答編集履歴

2

Array.prototype.reduce

2019/09/01 02:24

投稿

think49
think49

スコア18194

answer CHANGED
@@ -1,3 +1,5 @@
1
+ ### new Map で管理する
2
+
1
3
  同じカテゴリ群を持つデータをグループ化すると、管理性が良くなると思います。
2
4
  元のデータ構造を維持する理由がなければ、`new Map` のまま運用します。
3
5
 
@@ -45,4 +47,39 @@
45
47
  console.log(JSON.stringify(result)); // [["a","a","a",1,20190202],["a","b","a",1,20190101],["b","a","a",1,20190101],["a","a","c",1,20190101],["c","a","c",1,20190701],["b","b","b",1,20190101],["b","b","a",1,20190101],["b","a","b",1,20190101]]
46
48
  ```
47
49
 
48
- Re: tetsu777 さん
50
+ ### Array.prototype.reduce
51
+
52
+ データ構造を変えず、検索の為の中間オブジェクトをその都度生成するならば、`Array.prototype.reduce` が適していると思われます。
53
+ (前節のコードもそうですが、カテゴリ1~カテゴリ3は `String` 型であれば、使用できない文字はありません)
54
+
55
+ ```JavaScript
56
+ const array = [
57
+ ["a","a","a",1,"2019/01/01"],
58
+ ["a","b","a",1,"2019/01/01"],
59
+ ["b","a","a",1,"2019/01/01"],
60
+ ["a","a","c",1,"2019/01/01"],
61
+ ["c","a","c",1,"2019/01/01"],
62
+ ["b","b","b",1,"2019/01/01"],
63
+ ["b","b","a",1,"2019/01/01"],
64
+ ["c","a","c",1,"2019/07/01"],
65
+ ["b","a","b",1,"2019/01/01"],
66
+ ["a","a","a",1,"2019/02/02"]
67
+ ];
68
+
69
+ const lastUpdate = array.reduce((entries, current) => {
70
+ const keys = entries.keys,
71
+ values = entries.values,
72
+ currentKey = JSON.stringify([current[0],current[1],current[2]]),
73
+ index = keys.indexOf(currentKey);
74
+
75
+ if (index === -1) {
76
+ keys.push(currentKey), values.push(current);
77
+ } else if (values[index][4] <= current[4]) {
78
+ keys[index] = currentKey, values[index] = current;
79
+ }
80
+
81
+ return entries;
82
+ }, {keys: [], values: []}).values;
83
+
84
+ console.log(JSON.stringify(lastUpdate)); // [["a","a","a",1,"2019/02/02"],["a","b","a",1,"2019/01/01"],["b","a","a",1,"2019/01/01"],["a","a","c",1,"2019/01/01"],["c","a","c",1,"2019/07/01"],["b","b","b",1,"2019/01/01"],["b","b","a",1,"2019/01/01"],["b","a","b",1,"2019/01/01"]]
85
+ ```

1

typo修正

2019/09/01 02:24

投稿

think49
think49

スコア18194

answer CHANGED
@@ -1,4 +1,4 @@
1
- 同じカテゴリ群を持つデータをグループ化すると、管理性が良くなるといます。
1
+ 同じカテゴリ群を持つデータをグループ化すると、管理性が良くなるといます。
2
2
  元のデータ構造を維持する理由がなければ、`new Map` のまま運用します。
3
3
 
4
4
  ```JavaScript