Flattening a deeply nested array of literals in JavaScript


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
]

Updated on: 11-Dec-2020

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements