Flatten a multi-dimensional array
In the vast realm of JavaScript, arrays reign supreme as versatile containers of data. But when arrays nest within each other, navigating through their depths
In the vast realm of JavaScript, arrays reign supreme as versatile containers of data. But when arrays nest within each other, navigating through their depths can be a daunting task. Fear not, fellow coder! In this blog post, we embark on a quest to conquer nested arrays using the mighty power of the `reduce` Array method.
Imagine we're faced with an array filled with nested arrays, each containing a diverse array of elements:
const numbers = [
1,
[3, [2, 8, [12]], 9],
[5],
[12, 5],
[100, [23, 45, 83, [[1, 2], 54, 67], 54, [64]], 35, 1],
];Our mission? To transform this intricate network of nested arrays into a flat structure, where each element stands boldly on its own like below.
[1, 3, 2, 8, 12, 9, 5, 12, 5, 100, 23, 45, 83, 1, 2, 54, 67, 54, 64, 35, 1]Armed with the `reduce` method, we embark on our noble quest. Here's our strategy:
1. We traverse through each element in the array using the `reduce` method.
2. As we encounter each element, if it happens to be an array, unravel its contents one layer at a time.
3. With each recursive step, we collect the elements we find along the way and add them to our growing collection(accumulator).
4. With the power of `reduce`, we forge a path through the nested arrays, ensuring that no element goes unnoticed.
// 1st Apprach - Recurrsive
const flattenNumbers = (numbers) => {
return numbers.reduce((acc, num) => {
return acc.concat(Array.isArray(num) ? flattenNumbers(num) : num);
}, []);
};
console.log(flattenNumbers(numbers));In the above approach, we used the reduce array method to flatten an array.
// 2nd approach
console.log(numbers.flat(Infinity));With the flat method, we can flatten an array. For more details feel free to check out the javascript flat method.

Click to watch video tutorial
Thanks for reading!
Back to articles