
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
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;
Advertisements