How to Flatten a Nested Javascript Array

To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension.
There are certain situations in which the elements of an array are an array, generally referred to as nested arrays. For instance, the two-dimensional array below which represents student ids
let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];
and we need to return a new flat array with all the elements of the nested arrays in their original order.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
We can achieve this using different ways but we will focus on a few. Let’s see how they work.
1: concat() and apply()
In this example,this
is an empty array as seen in apply([], arr)
and arr
is the argument list we are passing (we’ve defined it above). So, we are saying take this argument and merge it with what you already got - another empty array, in this case. MSDN really explains concat()
and apply()
let flattened = [].concat.apply([], arr);// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
2: spread operator in ES6
Here, we are using the spread
operator to spread out the array. Then concatenate it with an empty array.
let flattened = [].concat(...arr);// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
3: array.reduce()
The reduce()
method as the name suggests reduces an array to a single value. I have explained in great detail what it is and how to use it. check out the article here
let flattened = arr.reduce((acc, curVal) => {return acc.concat(curVal)}, []);// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
What if we were working with deeply nested arrays?
While the above solutions flatten down to one level or can be modified to work for higher dimensions, let’s try a simpler approach 😄
Array.prototype.flat()
The flat()
method has an optional argument known as depth (the number of levels to flatten the array) and returns a new array - flattened version of the original array, removing any array hole (empty slot(s) in the array).
The default depth is 1. Otherwise, the passed argument defines the depth for flattening the array. You can also set the depth as Infinity (unlimited levels).
Let’s see some working examples.
Browser Support
Array.flat()
works in all modern browsers, but not IE. To support all browsers, you can use Babel to transpile your code to a previous ES version or use a polyfill to push back support.
If you don’t want to deal with Babel, or you don’t have a build step set up already, it might useful to try the
flatten()
,flattenDeep()
,flattenDepth()
functions provided by Lodash. You can use them individually without importing the whole library.
Conclusion
We have seen what flattening an array means, when we need to flatten an array and the various ways we can achieve it, using the different methods provided in the example.
Further Reading
Feel free to leave your comments and suggestions. Let’s keep the conversation going!