
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
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 a whitespaces and elements of two adjacent arrays should be separated by a comma.
Example
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 < arr.length; i++){ const el = arr[i]; const temp = el.join(' '); res += temp; if(i !== arr.length − 1){ res += ','; } }; return res; }; console.log(arrayToString(arr));
Output
And the output in the console will be −
0 0 0 −8.5 28 8.5,1 1 −3 0 3 12,2 2 −0.5 0 0.5 5.3
Advertisements