3

I have a nested array:

[1, 2, [3, 4, [5, [6]], 7], 8, 9]

How could I print it in an elegant way to look like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
budiDino
  • 13,044
  • 8
  • 95
  • 91

5 Answers5

2
function printArray(arr) {
    if ( typeof(arr) == "object") {
        for (var i = 0; i < arr.length; i++) {
            printArray(arr[i]);
        }
    }
    else console.log(arr);
}

printArray([1,2,[3,4,[5,[6]],7],8,9]);
Jayce444
  • 8,725
  • 3
  • 27
  • 43
1

You can try this, it will flatten your array.

let a = [1, 2, [3, 4, [5, [6]], 7], 8, 9];
const flatten = arr => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
console.log(flatten(a));

Actually, you can find it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Update 1:

Here is another solution.

function flatten(arr) {
    var x;
    x = JSON.stringify(arr);
    x = "[" + x.replace(/[\[\]]/g, "") + "]";
    return JSON.parse(x);
}
console.log(flatten(a));
Community
  • 1
  • 1
Yichong
  • 707
  • 4
  • 10
0

This is another way of doing it with ES6:

var nested = [1, 2, [3, 4, [5, [6]], 7], 8, 9];

var flat = [].concat(nested);

for(var i = 0; i < flat.length; i++) {
    if(Array.isArray(flat[i])) {
        flat.splice(i, 1, ...flat[i--]);  
    }
}

console.log(flat);
Yaser
  • 5,609
  • 1
  • 15
  • 27
0

@Yaser solution seems very elegant. Just in case you want to use a functional framework, here an example using ramda

const arr = R.flatten([1, 2, [3, 4, [5, [6]], 7], 8, 9]);
console.log(arr); //[1, 2, 3, 4, 5, 6, 7, 8, 9]
Hosar
  • 5,163
  • 3
  • 26
  • 39
0

When using node.js, the following gives me almost what you requested, except that the printed output has no spaces after the commas:

console.log('[%s]', [1, 2, [3, 4, [5, [6]], 7], 8, 9]);

Calling toString() on the array may be necessary to get the same results in other environments:

console.log('[%s]', [1, 2, [3, 4, [5, [6]], 7], 8, 9].toString());
cybersam
  • 63,203
  • 6
  • 53
  • 76