4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript:多重配列をflatにする関数

Last updated at Posted at 2018-03-12

ディープコピーと同様に考えるとflattenは:

  • 初期値[]のアキュムレータに配列の要素を順に連結していく(reduce)。
  • もし配列の要素が配列なら、要素をさらにflatにしてから連結(concat)。
  • そうでないなら要素をそのまま連結。

アロー関数で書くと:

const flatten =
  xs => xs.reduce(
      (acc, e) => Array.isArray( e ) ? acc.concat( flatten( e ) )
                                     : acc.concat( e )
      ,[]
    )
flatten([ 1, [ 2, 3 ], [ [ 4, 5 ], 6 ] ])
=> [ 1, 2, 3, 4, 5, 6 ]

参照:
Greedy flatten function for Array in JavaScript
function式で書かれている。中味は同じ。

あるいはスプレッド構文を使って

const flatten =
  xs => xs.reduce(
      (acc, e) => Array.isArray( e ) ? [...acc, ...flatten( e )]
                                     : [...acc, e ]
      ,[]
    )

こっちの方が直観的かも。見慣れれば。

4
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?