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
Flatten array to 1 line in JavaScript
Suppose, we have a nested array of numbers like this ?
const arr = [ [ 0, 0, 0, -8.5, 28, 8.5 ], [ 1, 1, -3, 0, 3, 12 ], [ 2, 2, -0.5, 0, 0.5, 5.3 ] ];
We are required to write a JavaScript function that takes in one such nested array of numbers. The function should combine all the numbers in the nested array to form a single string.
In the resulting string, the adjacent numbers should be separated by whitespaces and elements of two adjacent arrays should be separated by a comma.
Using Traditional Loop Method
The code for this will be ?
const arr = [
[ 0, 0, 0, -8.5, 28, 8.5 ],
[ 1, 1, -3, 0, 3, 12 ],
[ 2, 2, -0.5, 0, 0.5, 5.3 ]
];
const arrayToString = (arr = []) => {
let res = '';
for(let i = 0; i
0 0 0 -8.5 28 8.5,1 1 -3 0 3 12,2 2 -0.5 0 0.5 5.3
Using map() and join() (One Line Solution)
Here's a more concise approach using array methods that can flatten the array to a string in just one line:
const arr = [
[ 0, 0, 0, -8.5, 28, 8.5 ],
[ 1, 1, -3, 0, 3, 12 ],
[ 2, 2, -0.5, 0, 0.5, 5.3 ]
];
// One line solution
const result = arr.map(subArray => subArray.join(' ')).join(',');
console.log(result);
0 0 0 -8.5 28 8.5,1 1 -3 0 3 12,2 2 -0.5 0 0.5 5.3
How It Works
The one-line solution works by:
-
Step 1:
arr.map(subArray => subArray.join(' '))- Convert each sub-array to a string with space-separated values -
Step 2:
.join(',')- Join all the resulting strings with commas
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| Traditional Loop | Multiple lines | Good for beginners | Slightly faster |
| map() and join() | One line | More functional | Good performance |
Conclusion
Both methods achieve the same result. The map().join() approach provides a cleaner, one-line solution that's more functional in style, while the traditional loop offers more explicit control over the process.
