DEV Community

Purushothaman Raju
Purushothaman Raju

Posted on

Flattening a multidimensional array using Javascript

So as the title implies let’s see how to flatten an multidimensional array, As we know a multidimensional array looks something like this [[1,2],[3,4],[5,[6,7]]] and we would want to flatten this to something like this [1,2,3,4,5,6,7] since we know the expected output let’s get started.

First, we define a function called arrFlatten and declare a variable called flattendArray to store the flattened array. We will be using recursion since it’s an efficient solution for problems like these, inside the arrFlatten.

We define another function called recurseFlatten , which will loop over every item inside the array and identify if the array item is not an object, This check is added to ensure that we only add a number or string to the flattendArray. If the check returns false we push the array item into the flattendArray and finally return the flattendArray.

Here it the complete code for flattening an multidimensional array

const arrFlatten = (arr) => {
        let flattendArray = [];
        const recurseFlatten = (arr) => {
          for (let i = 0; i < arr.length; i++) {
            if (typeof arr[i] === "object") {
              recurseFlatten(arr[i]);
            } else {
              flattendArray.push(arr[i]);
            }
          }
        };
        recurseFlatten(arr);
        return flattendArray;
      };

let multiDimesionArray = [0, [1, 2], [3, 4], [5, 6, [7, 8]]];
 console.log(arrFlatten(multiDimesionArray));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)