Using recursion and a while
loop is on of the easier ways to do that
export default function flatten(value) {
const arr = []
const flat = (a) => {
let counter = 0
console.log(a)
while (counter < a.length) {
const val = a[counter]
if (Array.isArray(val)) {
return flat(val)
} else {
arr.push(val)
}
counter++
}
}
flat(value)
return arr
}
You also can do that using a reduce()
and array.concat()
export default function flatten(value) {
return value.reduce((acc, val) =>
Array.isArray(val)
? acc.concat(flatten(val))
: acc.concat(val),
[]);
}