LodashにgroupByがあるので瞬殺です。
オブジェクトになるじゃねーか!
なのでvaluesと組み合わせましょうね。
Online Lodash Testerで調べてみましょう。
ついでにチェーン記法を使ってかっこよく仕上げます。
js
1const data = [
2 {fruit: 'apple', price: 100},
3 {fruit: 'orange', price: 120},
4 {fruit: 'apple', price: 200},
5 {fruit: 'orange', price: 130},
6 {fruit: 'apple', price: 140},
7];
8
9result = _(data)
10 .groupBy(it => it.fruit)
11 .values()
12 .value()
結果はご覧の通りです。
json
1[
2 [
3 {
4 "fruit": "apple",
5 "price": 100
6 },
7 {
8 "fruit": "apple",
9 "price": 200
10 },
11 {
12 "fruit": "apple",
13 "price": 140
14 }
15 ],
16 [
17 {
18 "fruit": "orange",
19 "price": 120
20 },
21 {
22 "fruit": "orange",
23 "price": 130
24 }
25 ]
26]
【おまけ】 ネイティブJSで頑張る
ネイティブJSにはgroupByなどという軟弱なものはありませんので、
reduceでチクチク実装する必要があります。
ネイティブJSにもES2017という比較的新しい機能としてObject.values実装されていますので、
一度オブジェクトを経由するのが分かりやすいですね。
js
1const data = [
2 {fruit: 'apple', price: 100},
3 {fruit: 'orange', price: 120},
4 {fruit: 'apple', price: 200},
5 {fruit: 'orange', price: 130},
6 {fruit: 'apple', price: 140},
7];
8
9const result = Object.values(
10 data.reduce((obj, it) => {
11 if (!obj[it.fruit]) obj[it.fruit] = [];
12 obj[it.fruit].push(it);
13 return obj;
14 }, {})
15);
16
17console.log(JSON.stringify(result, null, 2));
結果
json
1[
2 [
3 {
4 "fruit": "apple",
5 "price": 100
6 },
7 {
8 "fruit": "apple",
9 "price": 200
10 },
11 {
12 "fruit": "apple",
13 "price": 140
14 }
15 ],
16 [
17 {
18 "fruit": "orange",
19 "price": 120
20 },
21 {
22 "fruit": "orange",
23 "price": 130
24 }
25 ]
26]
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/27 15:48