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
Selected Reading
Join in nested array in JavaScript
Joining elements from nested arrays in JavaScript requires flattening the array structure first. This article explores different approaches to join nested array elements with a semicolon separator.
The Problem
Consider this nested array:
const arr = ['zero', ['one', 'two', 'three', ['four', ['five', 'six', ['seven']]]]];
console.log("Original nested array:", arr);
Original nested array: [ 'zero', [ 'one', 'two', 'three', [ 'four', [Array] ] ] ]
We need to extract all elements and join them with semicolons to get:
zero;one;two;three;four;five;six;seven;
Using flat() Method (Modern Approach)
The flat(Infinity) method flattens arrays to any depth:
const arr = ['zero', ['one', 'two', 'three', ['four', ['five', 'six', ['seven']]]]];
const joinNestedArray = (nestedArr) => {
return nestedArr.flat(Infinity).join(';') + ';';
};
console.log(joinNestedArray(arr));
zero;one;two;three;four;five;six;seven;
Using Recursive Approach
For environments without flat() support, use recursion:
const arr = ['zero', ['one', 'two', 'three', ['four', ['five', 'six', ['seven']]]]];
const buildStringRecursive = (arr = [], result = []) => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
buildStringRecursive(arr[i], result);
} else {
result.push(arr[i]);
}
}
return result.join(';') + ';';
};
console.log(buildStringRecursive(arr));
zero;one;two;three;four;five;six;seven;
Using JSON.stringify() Approach
A creative approach using JSON parsing:
const arr = ['zero', ['one', 'two', 'three', ['four', ['five', 'six', ['seven']]]]];
const joinWithJSON = (nestedArr) => {
return JSON.stringify(nestedArr)
.replace(/[\[\]"]/g, '')
.replace(/,/g, ';') + ';';
};
console.log(joinWithJSON(arr));
zero;one;two;three;four;five;six;seven;
Comparison
| Method | Browser Support | Performance | Readability |
|---|---|---|---|
flat(Infinity) |
ES2019+ | Best | Excellent |
| Recursive | Universal | Good | Good |
| JSON.stringify() | Universal | Moderate | Fair |
Conclusion
Use flat(Infinity) for modern environments due to its simplicity and performance. For older browsers, the recursive approach provides reliable cross-platform compatibility.
Advertisements
