Flatten a nested array using javascript

You can loop through the array entries, check if it’s an array with isArray() and recursively flatten the entries of the array as below:

function deepFlattenArray(arr) {
   const finalArray = [];
   // Loop through the array contents
   for (let i = 0; i < arr.length; i++) {
     if (Array.isArray(arr[i])) {
       // Recursively flatten entries that are arrays and push into the finalArray
       finalArray.push(…deepFlattenArray(arr[i]));
     } else {
       // Push entries that are not arrays
       finalArray.push(arr[i]);
     }
   }
   return finalArray;
 }
 console.log(deepFlattenArray([1, [2], [3, [[4]]]]));  //[ 1, 2, 3, 4 ]

Leave a Comment

Your email address will not be published. Required fields are marked *