Convert nested array to string - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 15-Sep-2020 08:58:44
Advertisements