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]
5
  • 1
    What is your not elegant way? Commented Jan 20, 2017 at 1:40
  • "print" as in console.log or "print" like output in html? Commented Jan 20, 2017 at 1:41
  • JSON.parse("[" + [1,2,[3,4,[5,[6]],7],8,9].join(",") + "]") Commented Jan 20, 2017 at 1:58
  • This is called "flattening". Google for that. Commented Jan 20, 2017 at 2:08
  • Also take a look at Underscore's _.flatten. Commented Jan 20, 2017 at 2:30

5 Answers 5

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

I would just change document.write to console.log. It's very bad practice to use document.write
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));

Comments

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]

Comments

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

2 Comments

The result is : [1, 2, 3, 4, Array[2], 7, 8, 9] in chrome or [1, 2, 3, 4, [5, [6]], 7, 8, 9] in firefox.
yeah saw it, updated the answer with a working solution @Y.C.
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());

2 Comments

For me this displays [Array[5]] in the console.
See my updated answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.