How to Flatten An Array in JavaScript

Claire DeBoer
3 min readJun 9, 2021

Flattening an array means reducing a multidimensional or nested array (an array where some elements are themselves arrays) to one single array with elements in the original order. The first two methods I’ll discuss, spread and reduce(), work on two dimensional arrays, meaning arrays that are one level nested. The second two ways of handling flattening an array, using flat() and recursion, work on arrays nested at any level.

Flattening an array is a classic technical interview question that I’ve been stumped on myself. I will not be fooled again and I hope you won’t either after reading my simple overview.

Using Spread ES6 (works on two dimensional arrays)

We use the spread operator to spread out the nested array and concatenate it with an empty array.

2D Array Input: [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]]

2D Array Output: [3, 2, 1, 4, 6, 5, 9, 7, 8]

Using Reduce (works on two dimensional arrays)

The reduce() method reduces an array to a single value using a callback function. The accumulator is the thing you’re shoveling into, in this case a new array. The currentValue is the current element in the array. The initialValue is the initial value to be passed to the function and in this case we set it to an empty array. The reducer callback will be executed on each element.

The basic syntax is like this: array.reduce(callback(accumulator, currentValue), initialValue);

2D Array Input: [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]]

2D Array Output: [3, 2, 1, 4, 6, 5, 9, 7, 8]

Using Flat (works on an array of any depth)

Introduced as of ES2019, flat() returns a new array which is the flattened version of the original, removing any empty slots in the array. It works on most modern browsers. There is an optional argument known as depth which is the number of levels to flatten the array. Using ‘Infinity’ as the depth argument means flatten all levels to a one-dimensional array which allows you to use this method on an array of any depth unlike spread and reduce. Pretty cool.

3D Array Input: [[3, 2, 1, [3, 4]], [4, 6, 5], [], [9, 7, 8]]

3D Array Output: [3, 2, 1, 3, 4, 4, 6, 5, 9, 7, 8]

Using Recursion (works on an array of any depth)

This is the old school way of flattening an array of any depth which was the go-to before flat() was introduced. See my explanation of reduce above. This method uses the same logic as that explanation, but instead of concatenating the currentValue with the accumulator, you first check if the currentValue is an array. If it is an array, then call your recursiveFlatten function recursively. If it is not an array, then go ahead and concatenate the currentValue with the accumulator.

3D Array Input: [[3, 2, 1, [3, 4]], [4, 6, 5], [], [9, 7, 8]]

3D Array Output: [3, 2, 1, 3, 4, 4, 6, 5, 9, 7, 8]

--

--