flatメソッド
flatメソッドは、
多次元配列の入れ子レベルを減らします。
配列を一次元にしたり、指定された数だけ
次元数を減らしたりすることができます。
構文
let newArray = 配列.flat(平坦化のレベル);
例
引数に何も値を指定せずに新しい配列を取得してみましょう:
let arr = ['a', 'b', ['c', 'd']];
let res = arr.flat();
console.log(res);
このコードを実行すると、サブ配列が1レベル上げられた 結果が得られます:
['a', 'b', 'c', 'd']
例
次に、flatメソッドを2レベルの入れ子を持つ
配列に適用してみましょう:
let arr = ['a', 'b', ['c', 'd', ['e', 'f']]];
let res = arr.flat();
console.log(res);
コード実行結果:
['a', 'b', 'c', 'd', ['e', 'f']]
例
平坦化のレベルを指定してみましょう:
let arr = ['a', 'b', ['c', 'd', ['e', 'f']]];
let res = arr.flat(2);
console.log(res);
コード実行結果:
['a', 'b', 'c', 'd', 'e', 'f']
例
入れ子のレベルを気にせず、配列全体を結合したい場合は、
パラメータとしてInfinityを使用します:
let arr = ['a', 'b', ['c', 'd', ['e', 'f', ['g', 'h', ['i']]]]];
let res = arr.flat(Infinity);
console.log(res);
コード実行結果:
[
'a', 'b', 'c',
'd', 'e', 'f',
'g', 'h', 'i'
]
関連項目
-
関数適用後の要素からなる配列を返す、
メソッド
flatMap