How to Flatten an Array in JavaScript
Flattening an array is the process of merging multi-dimensional subarrays into a single, one-dimensional array.
Example
Input:
[[[1, [1.1]], 2, 3], [4, 5]]
Output:
[1, 1.1, 2, 3, 4, 5]
Using ES2019 Methods
In ES2019, two new methods were introduced to flatten arrays:
flat()
flatMap()
Using flat()
flat()
merges multi-dimensional subarrays into a one-dimensional array. By default, it flattens only one level deep, but you can specify the depth.
[1, 2, [3, 4]].flat();
// Output: [1, 2, 3, 4]
[1, 2, [3, 4], [[5]]].flat(2);
// Output: [1, 2, 3, 4, 5]
For deep flattening, pass Infinity
as the depth.
[[[1, [1.1]], 2, 3], [4, 5]].flat(Infinity);
// Output: [1, 1.1, 2, 3, 4, 5]
Using flatMap()
flatMap()
combines map()
and flat()
into one method, performing both operations together.
['Pratap Das', 'Learn JavaScript'].flatMap(e => e.split(' '));
// Output: ['Pratap', 'Das', 'Learn', 'JavaScript']
Alternative Flattening Methods
Using Spread Operator (For Two-Dimensional Arrays)
The spread operator spreads out the nested array and concatenates it with an empty array.
const spreadFlatten = (array) => {
let flatArray = [];
return flatArray.concat(...array);
};
Using Reduce (For Two-Dimensional Arrays)
The reduce()
method can also be used to flatten arrays by concatenating each nested array.
const reduceFlatten = (array) => {
const reducer = (accumulator, currentValue) => accumulator.concat(currentValue);
return array.reduce(reducer, []);
};
Using Flat (For Arrays of Any Depth)
The flat()
method works for arrays of any depth by passing Infinity
as the depth.
const flatFlatten = (array) => {
return array.flat(Infinity);
};
Using Recursion (For Arrays of Any Depth)
The recursive approach uses reduce()
to flatten arrays of any depth.
const recursiveFlatten = (array) => {
const reducer = (accumulator, currentValue) => {
return accumulator.concat(Array.isArray(currentValue) ?
recursiveFlatten(currentValue) : currentValue);
};
return array.reduce(reducer, []);
};
Polyfill
You can create a custom function to flatten arrays if you don't want to rely on modern features.
ES6 Example
const flatten = (arr) => {
return arr.reduce((flat, toFlatten) =>
flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), []);
};
Traditional Method
const flatten = function(arr, result = []) {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, result);
} else {
result.push(value);
}
}
return result;
};