LoginSignup
34
13

More than 3 years have passed since last update.

[JavaScript/TypeScript] flat()を使わずに配列をflattenする

Last updated at Posted at 2019-12-25

[[0, 1], 2, [3, 4]] のようなネストしたりしなかったりする配列をフラットにしたい場合、ES2019 以降だと Array.prototype.flat() が使えるけど Node.js 10 は対応してないので他の方法を考えた。(意外と簡単だった)

const nested = [[0, 1], 2, [3, 4]]
const flat = [].concat(...nested) // => [0, 1, 2, 3, 4]

スプレッド演算子を使うと [].concat([0, 1], 2, [3, 4]) のように呼び出してくれるので結合されてフラットな配列になります。

34
13
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
34
13