JavaScriptの配列関係のコード集です。何かを作っていたときの副産物の塊です。
最後の要素を取得する
const array1 = ["a", "b", "c", "d"]
array1.slice(-1)[0]
// "d"
最初の要素を特別扱いして二次元配列→2要素配列の配列[[a, b, c, ...], [d, e, f, ...], ...]→[[a, b], [a, c], [d, e], [d, e], ...]
slice
const items = [
["2020/05/31", "A", "B", "C"],
["2020/05/31", "D", "E", "F"],
["2020/06/01", "G", "H", "I"],
];
items.flatMap(raw => raw.slice(1).map(item => [raw[0], item ]));
分割代入と可変長引数
const items = [
["2020/05/31", "A", "B", "C"],
["2020/05/31", "D", "E", "F"],
["2020/06/01", "G", "H", "I"],
];
items.flatMap(([first, ...others]) => others.map(other => [first, other]));
出力
/*
(9) […]
0: Array [ "2020/05/31", "A" ]
1: Array [ "2020/05/31", "B" ]
2: Array [ "2020/05/31", "C" ]
3: Array [ "2020/05/31", "D" ]
4: Array [ "2020/05/31", "E" ]
5: Array [ "2020/05/31", "F" ]
6: Array [ "2020/06/01", "G" ]
7: Array [ "2020/06/01", "H" ]
8: Array [ "2020/06/01", "I" ]
length: 9
*/
最初の要素を特別扱いして二次元配列→2要素配列の配列[[a, b, c, ...], [d, e, f, ...], ...]→[[b,a], [c, a], [e, a], [e, a], ...]
flatMapとslice
items.flatMap(raw => raw.slice(1).map(item => [item, raw[0]]));
分割代入と可変長引数
items.flatMap(([first, ...others]) => others.map(other => [other, first]));
出力
/*
(9) […]
0: Array [ "A", "2020/05/31" ]
1: Array [ "B", "2020/05/31" ]
2: Array [ "C", "2020/05/31" ]
3: Array [ "D", "2020/05/31" ]
4: Array [ "E", "2020/05/31" ]
5: Array [ "F", "2020/05/31" ]
6: Array [ "G", "2020/06/01" ]
7: Array [ "H", "2020/06/01" ]
8: Array [ "I", "2020/06/01" ]
length: 9
*/
最初の要素を特別扱いして二次元配列→2要素オブジェクトの配列[[a, b, c, ...], [d, e, f, ...], ...]→[{key1:a, key2:b}, {key1:a, key2:c}, {key1:d, key2:e}, {key1:d, key2:e}, ...]
slice
const items = [
["2020/05/31", "A", "B", "C"],
["2020/05/31", "D", "E", "F"],
["2020/06/01", "G", "H", "I"],
];
items.flatMap(raw => raw.slice(1).map(item => ({key1: raw[0], key2: item})));
分割代入と可変長引数
const items = [
["2020/05/31", "A", "B", "C"],
["2020/05/31", "D", "E", "F"],
["2020/06/01", "G", "H", "I"],
];
items.flatMap(([first, ...others]) => others.map(other => ({key1: first, key2: other})));
出力
/*
(9) […]
0: Object { key1: "2020/05/31", key2: "A" }
1: Object { key1: "2020/05/31", key2: "B" }
2: Object { key1: "2020/05/31", key2: "C" }
3: Object { key1: "2020/05/31", key2: "D" }
4: Object { key1: "2020/05/31", key2: "E" }
5: Object { key1: "2020/05/31", key2: "F" }
6: Object { key1: "2020/06/01", key2: "G" }
7: Object { key1: "2020/06/01", key2: "H" }
8: Object { key1: "2020/06/01", key2: "I" }
length: 9
*/
- ラムダ式でオブジェクトリテラルを使うとき、直接
() => {...}
とすると関数と誤解されてエラーが発生します。() => {return {...};}
または() => ({...})
で対処できます。