
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Flatten an array in JavaScript.
- How to deep flatten an array in JavaScript?
- Function to flatten array of multiple nested arrays without recursion in JavaScript
- Best way to flatten an object with array properties into one array JavaScript
- How to use a line break in array values in JavaScript?
- How to Flatten JavaScript objects into a single-depth Object?
- Merging nested arrays to form 1-d array in JavaScript
- Flatten Tuples List to String in Python
- Flatten 2D Vector in C++
- How to flatten a Docker image?
- Flatten Binary Tree to Linked List in C++
- How to flatten a shallow list in Python?
- Flatten tuple of List to tuple in Python
- Javascript Program to Count 1’s in a sorted binary array
- How to Flatten a Matrix using numpy in Python?

Advertisements