Flatten a multidimension array

Flattening a multidimensional array is a process of taking an array with multiple sub-arrays and returning a single array with all the values of the original arrays combined. This can be done by looping through each sub-array and pushing each element into a single array.

//Flatten a multi-dimensional array
function flattenArray(arr) { 
    let flatArray = [];
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            flatArray = [...flatArray, ...flattenArray(arr[i])];
        } else {
    return flatArray;

For example, given the array [1, [2, [3, 4], 5], 6], the flattened array would be [1, 2, 3, 4, 5, 6]. The code example above is written in JavaScript and uses a recursive approach to loop through all the sub-arrays and push each element into a single array.

Another way to flatten a multidimensional array is to use the reduce method. This works similarly to a for loop but it is a bit more concise and can be written in one line of code. Here is an example below.

//Flatten a multi-dimensional array using reduce
let flattenedArray = arr.reduce((acc, cur) => 
    Array.isArray(cur) ? [...acc, ...flattenArray(cur)] : [...acc, cur], []);

The reduce method starts with an empty array and then loops through each element of the original array. If the element is an array, it will be flattened and added to the accumulator array. If it is not an array, it will be pushed into the accumulator array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]