Flattening a deeply nested array of literals in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a nested array of literals as the only argument. The function should construct a new array that contains all the literal elements present in the input array but without nesting.

For example −

If the input array is −

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

Then the output array should be −

const output = [1, 3, 5, 6, 7, 6, 5, 4, 3, 4];

Example

Following is the code −

const arr = [
   1, 3, [5, 6, [7, [6, 5], 4], 3], [4]
];
const flattenArray = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(Array.isArray(el)){
         res.push(...flattenArray(el));
      }else{
         res.push(el);
      };
   };
   return res;
};
console.log(flattenArray(arr));

Output

Following is the output on console −

[
   1, 3, 5, 6, 7,
   6, 5, 4, 3, 4
]
raja
Published on 11-Dec-2020 14:05:23
Advertisements