Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert nested array to string - JavaScript
Converting a nested array to a string in JavaScript involves flattening all nested elements and concatenating their values. This is commonly needed when processing complex data structures.
Problem Statement
We need to write a JavaScript function that takes a nested array of literals and converts it to a single string by concatenating all values, regardless of nesting depth.
const arr = [
'hello', [
'world', 'how', [
'are', 'you', [
'without', 'me'
]
]
]
];
Method 1: Using Recursive Function
The most straightforward approach is to use recursion to traverse each level of nesting:
const arr = [
'hello', [
'world', 'how', [
'are', 'you', [
'without', 'me'
]
]
]
];
const arrayToString = (arr) => {
let str = '';
for(let i = 0; i
helloworldhowareyouwithoutme
Method 2: Using Array.flat() and join()
A more modern approach uses the built-in flat() method with infinite depth:
const arr = [
'hello', [
'world', 'how', [
'are', 'you', [
'without', 'me'
]
]
]
];
const arrayToString = (arr) => {
return arr.flat(Infinity).join('');
};
console.log(arrayToString(arr));
helloworldhowareyouwithoutme
Method 3: Using toString() Method
JavaScript's built-in toString() method also flattens arrays, though it adds commas by default:
const arr = [
'hello', [
'world', 'how', [
'are', 'you', [
'without', 'me'
]
]
]
];
const arrayToString = (arr) => {
return arr.toString().replace(/,/g, '');
};
console.log(arrayToString(arr));
helloworldhowareyouwithoutme
Comparison
| Method | Performance | Browser Support | Readability |
|---|---|---|---|
| Recursive Function | Good | All browsers | Medium |
| Array.flat() + join() | Best | ES2019+ | High |
| toString() + replace() | Good | All browsers | Medium |
Conclusion
For modern applications, use Array.flat(Infinity).join('') as it's the most concise and performant. For legacy browser support, the recursive approach provides reliable cross-browser compatibility.
