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

Updated on: 21-Nov-2020

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements