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]
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]
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]);
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
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));
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 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]
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());