Join in nested array in JavaScript


Suppose, we have a nested array like this −

const arr = ['zero', ['one', 'two' , 'three', ['four', ['five', 'six', ['seven']]]]];

We are required to write a JavaScript function that takes in a nested array. Our function should then return a string that contains all the array elements joined by a semicolon (';')

Therefore, for the above array, the output should look like −

const output = 'zero;one;two;three;four;five;six;seven;';

Example

The code for this will be −

const arr = ['zero', ['one', 'two' , 'three', ['four', ['five', 'six', ['seven']]]]];
const buildString = (arr = [], res = '') => {
   for(let i = 0; i < arr.length; i++){
      if(Array.isArray(arr[i])){
         return buildString(arr[i], res);
      }
      else{
         res += `${arr[i]};`
      };
   };
   return res;
};
console.log(buildString(arr));

Output

And the output in the console will be −

zero;one;two;three;four;five;six;seven;

Updated on: 23-Nov-2020

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements