LoginSignup
4
1

More than 3 years have passed since last update.

Array.prototype.mapとArray.prototype.flatMap

Last updated at Posted at 2019-06-27

tl;dr

Array.prototype.flatArray.prototype.flatMapES2019から導入される。
サンプルコードを記載する。

Array.prototype.flatの例
Array.prototype.flatMapの例

Array.prototype.flatの例

// このような多階層の配列があるとする
const array = [1,[2,[3]]];


// これをArray#flatすると
const arrayFlatten = array.flat(); // [1,[2,3]]

となる。


// もういちどやれば
arrayFlatten.flat(); // [1,2,3]

となる。

この、flatする回数は引数で指定可能で、デフォルトはの引数は1となっている。


const array2 = [4,[5,[6]]];
array2.flat(1); // [4,[5,6]]
array2.flat(2); // [4,5,6]

再帰的に実行し、全く平坦にする場合はこのようにする


const array3 = [7,[8,[9[10]]]];
array3.flat(Infinity); // [7,8,9,10]

Array.prototype.flatMapの例

ここで、duplicateという関数を定義する。duplicateは、引数を複製し、配列に入れて返す関数とする。


const duplicate = x => [x, x];

// これを配列に適用すると次のようになる
[1,2,3].map(duplicate); // [[1,1],[2,2],[3,3]

// さらにflatする場合は、
[1,2,3].map(duplicate).flat(); // [1,1,2,2,3,3]

//とすればよいが、ここでflatMapの出番となる。
[1,2,3].flatMap(duplicate);  // [1,1,2,2,3,3]
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1