How to flatten multidimensional JavaScript arrays
June 22, 2018
If you want to flatten an array, you can use this simple ES6 spread syntax:
const arr = [['Dolores'], ['William'], ['Ford'], ['Bernard']]
const flat = [].concat(...arr)
console.log(flat) // ['Dolores', 'William', 'Ford', 'Bernard']
If you want to flatten an array full of arrays that might also contain arrays – a deep array structure – you can use this slightly more advanced version:
const deepArray = [
[['Dolores', 'Wyatt'], 'Teddy'],
[['William', 'Man In Black'], 'Emily'],
[['Bernard', 'Arnold'], 'Charlie'],
[['Ford', 'Fordnard'], 'Maeve']
]
// Flatten deep arrays
function flatten(x) {
return Array.isArray(x)
? [].concat(...x.map(flatten))
: x
}
console.log(flatten(deepArray)) // ['Dolores', 'Wyatt', 'Teddy', ...]
concat
is just a method for joining arrays together. The real magic comes in with the recursive flatten(...)
function, which accepts an item that's either an array, or not an array. I feel it's best explained in this pseudocode:
FLATTEN
Is this an array?
YES: FLATTEN its children.
NO: Leave it alone.
Now that I type that, it sounds a little harsh...