0
1

More than 3 years have passed since last update.

JS 配列内の最初の配列のみ展開する

Last updated at Posted at 2020-08-15

lodathのflattenメゾッドを作ってみた

▶︎ lodath flatten

const flatten = (array) => {
  const flattenArray = []
  for (let i = 0; i < array.length; i++) {
    const object = array[i]
  //Array.isArray => 配列か判定
    const isArray = Array.isArray(object)
    if (isArray) {
      flattenArray.push(...object)
    } else {
      flattenArray.push(object)
    }
  }
  return flattenArray
}

console.log(flatten([0, [2, 2, [3, [4]], 5], 1]))
// => [ 0, 2, 2, [ 3, [ 4 ] ], 5, 1 ]

flatMapを使えばすごくシンプルにかけた

こんな使い方できるとは・・!
自分が無知すぎて知らなかった。。ご教授頂き@YutaUraさんありがとうございます!

const arr = [0, [2, 2, [3, [4]], 5], 1]
console.log(arr.flatMap((v) => v))

// => [ 0, 2, 2, [ 3, [ 4 ] ], 5, 1 ]
0
1
4

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
0
1