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),
[]);
}
Top comments (2)
Why not just use the built-in Array.prototype.flat? It's faster, and has the option of flattening
n
levelsI posted this, because sometimes people need to know how to do it manually on code challenges :)