Convert nested array to string - JavaScript


We are required to write a JavaScript function that takes in a nested array of literals and converts it to a string by concatenating all the values present in it to the string

const arr = [
   'hello', [
      'world', 'how', [
         'are', 'you', [
            'without', 'me'
         ]
      ]
   ]
];

Example

Let’s say the following is our nested array −

const arr = [
   'hello', [
      'world', 'how', [
         'are', 'you', [
            'without', 'me'
         ]
      ]
   ]
];
const arrayToString = (arr) => {
   let str = '';
   for(let i = 0; i < arr.length; i++){
      if(Array.isArray(arr[i])){
         str += arrayToString(arr[i]);
      }else{
         str += arr[i];
      };
   };
   return str;
};
console.log(arrayToString(arr));

Output

Following is the output in the console −

helloworldhowareyouwithoutme

Updated on: 15-Sep-2020

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements