
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Multi-Dimensional Array to String in 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. Moreover, we should append a whitespace at the end of each string element while constructing the new string.
Let’s write the code for this function −
Example
The code for this will be −
const arr = [ 'this', [ 'is', 'an', [ 'example', 'of', [ 'nested', 'array' ] ] ] ]; 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
The output in the console −
this is an example of nested array
Advertisements