Function to flatten array of multiple nested arrays without recursion in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a nested array of numbers like this −

const arr = [1, 4, 5, [
   5, 6, [
      6, 19, 5, [5]
   ], [5, 7, 6, [6, 8]], 8
], 6];

We are required to write a JavaScript function that takes a nested array, ideally nested to any arbitrary level.

Our function should then prepare and return a new array that is nothing just a flattened version of the input array.

There are two conditions that we are asked to avoid while writing our function −

  • We cannot make use of any custom recursive function anywhere in our code.

  • We cannot make use of the Array.prototype.flat() method in our code.

Example

The code for this will be −

const arr = [1, 4, 5, [
   5, 6, [
      6, 19, 5, [5]
   ], [5, 7, 6, [6, 8]], 8
], 6];
const flattenWithoutRecursion = (arr = []) => {
   const res = [];
   let level = 0, ref = [arr], counter = [0];
   while(level >= 0){
      if (counter[level] >= ref[level].length) {
         level--;
         continue;
      };
      if (Array.isArray(ref[level][counter[level]])) {
         ref[level + 1] = ref[level][counter[level]]
         counter[level]++;
         level++;
         counter[level] = 0;
         continue;
      };
      res.push(ref[level][counter[level]]);
      counter[level]++;
   };
   return res;
};
console.log(flattenWithoutRecursion(arr));

Output

And the output in the console will be −

[
   1, 4, 5, 5, 6, 6,
   19, 5, 5, 5, 7, 6,
   6, 8, 8, 6
]
raja
Published on 21-Nov-2020 10:27:12
Advertisements