This succinct, example-based article will walk you through 4 different approaches to flattening a nested array in JavaScript. No need to procrastinate anymore; let’s roll up our sleeves and start!
Using the flat() method
The Array.prototype.flat() method returns a new array with all sub-array elements concatenated into it recursively.
Example:
const array = [
['s', 'l', 'i', 'n', 'g'],
['a', 'c', 'd', 'e', 'm', 'y'],
];
const flattened = array.flat();
console.log(flattened);
Output:
[
's', 'l', 'i', 'n',
'g', 'a', 'c', 'd',
'e', 'm', 'y'
]
Using the reduce() method
The example below demonstrates how to use the Array.prototype.reduce() method to flatten the multidimensional array recursively:
const multiDimensionalArr = [
[1, 2],
[3, 4, [5, 6]],
];
const flattenArray = (arr) => {
return arr.reduce(
(acc, val) =>
Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val),
[]
);
};
const flatArr = flattenArray(multiDimensionalArr);
console.log(flatArr);
Output:
[ 1, 2, 3, 4, 5, 6 ]
Using a loop
Loops can help us solve a multitude of problems, and in this situation too.
This example uses a for loop to flatten a given array:
const array = [1, 2, [3, 4], [5, 6, 7]];
const flattened = [];
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
// concatenate sub-array elements to flattened
flattened.push(...array[i]);
} else {
// push single element to flattened
flattened.push(array[i]);
}
}
console.log(flattened);
Output:
[ 1, 2, 3, 4,5, 6, 7 ]
Using the flatMap() method
The flatMap() method is the combination of the flat() and the map() methods. You can use it to quickly flatten a multidimensional array.
Example:
const array = [[1], [2], [3], [4, 5]];
const flattened = array.flatMap(x => x);
console.log(flattened);
Output:
[ 1, 2, 3, 4, 5 ]
Real-World Use Cases
Flattening an array can help simplify complex data structures and make them easier to work with. Some real-world use cases are:
- Data Processing: While processing data in a JavaScript application, you may need to flatten an array of objects into a flat array to perform some operations like sorting, filtering, or grouping.
- De-duplication: When you have an array containing multiple sub-arrays, flattening the array allows you to remove duplicates and obtain only unique values.
- Recursive Rendering: When working with Vue or other front-end frameworks, flattening an array can help you recursively render components.
Happy coding & have a nice day!