How to flatten multidimensional JavaScript arrays

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…

About the author

I'm Mark Thomas Miller, a full stack engineer and designer currently working at ConvertKit. (We're hiring!) People like Arnold Schwarzenegger, Lindsey Stirling, and Tim Ferriss use features I've built to connect with their fans. I'm currently geeking out about Svelte, mechanical keyboards, and minimalist UI design, and replaying Ocarina of Time.