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 ]