0

I have a multidimensional array in javascript that I would like to be able to turn into a string while preserving brackets. I have taken a look at other questions such as javascript - Convert array to string while preserving brackets and the answers there didn't help me much.

My array could look like the following:

[[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]]

When I print the array I see:

0,0,1,1,1,0,0,4,1,0,1,5,0,1,1,3,1,1,0,6,0,1,0,2

The output that I am expecting is what the original array looks like.

I have also tried the following code:

alert("[[" + myArray.join("],[") + "]]");

This works for almost everything, I get an output of:

[[0,0,1,1],[1,0,0,4],[1,0,1,5], ...

And I would like to see what the origional array looks like with the brackets. I would also like to stay away from JSON.stringify(); and JSON.parse();

8
  • 2
    Question is unclear, what is the input you are providing and the output you are expecting? And why not using JSON.stringify? Commented Aug 28, 2018 at 15:51
  • I would do a BFS function. Commented Aug 28, 2018 at 15:51
  • 3
    It seems JSON.stringify would provide exactly what you are looking for, being able to see what the array looks like with the brackets. Why the avoidance of JSON.stringify? Commented Aug 28, 2018 at 15:52
  • 2
    If your array is structured correctly, JSON.stringify() and JSON.parse() is literally what you're describing. Commented Aug 28, 2018 at 15:59
  • 3
    @DMVerfurth, JSON.parse on a stringified array will convert it back to an array (using a simple nested array with 0 in it): Array.isArray(JSON.parse(JSON.stringify([[0]]))) Commented Aug 28, 2018 at 16:00

1 Answer 1

1

JSON.stringify() and JSON.parse() will do exactly what you ask for. Try it out:

var arr = [[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]];
var str = JSON.stringify(arr);
alert(str);
var parsed = JSON.parse(str);
alert(parsed);
console.log(parsed);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.