Array flattening using loops and recursion in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript array function that takes in a nested array with false values as well and returns an array with all the elements present in the array without any nesting.

For example: If the input is −

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];

Then the output should be −

const output = [1, 2, 3, 4, 5, false, 6, 5, 8, null, 6];

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];
const flatten = function(){
   let res = [];
   for(let i = 0; i < this.length; i++){
      if(Array.isArray(this[i])){
         res.push(...this[i].flatten());
      }else{
         res.push(this[i]);
      };
   };
   return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());

Output

The output in the console will be −

[
   1, 2, 3, 4,
   5, 5, false, 6,
   5, 8, null, 6
]
raja
Published on 20-Oct-2020 15:17:33
Advertisements