2

When I create a nested array, say:

let x = [[0, 1], 2, [3, [4, 5]]]; 

and convert it to a string with .toString():

x.toString();
-> "0,1,2,3,4,5"

It doesn't preserve the nested structure of the array. I would like to get something like:

x.toString();
-> "[0,1],2,[3,[4,5]]"

Is there any smarter way of doing this other than looping through elements of x, testing if an element is an array etc.?

3
  • 3
    Have you tried JSON.stringify(x)? Commented Sep 1, 2019 at 3:35
  • I hadn't thought about using stringify, and then I could just substring out the first and last brackets... Commented Sep 1, 2019 at 3:39
  • 1
    JSON.stringify(x).slice(1, -1) Commented Sep 1, 2019 at 5:17

2 Answers 2

3

You can use JSON.stringify and replace

 ^\[|\]$

enter image description here

let x = [[0, 1], 2, [3, [4, 5]]]; 

let final = JSON.stringify(x)

// with regex
console.log(final.replace(/^\[|\]$/g,''))

// without regex
console.log(final.slice(1, -1))

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

4 Comments

Or just do a substring via slice?
I'll accept this in a minute when it will let me :)
I hadn't thought about using regex, I was just going to substring or slice like @Li357 commented. That's an interesting approach.
@Li357 yeah fair thing to do, add that too :)
1

Or possibly use a generator to build up a string manually:

 function* asNested(array) {
    for(const el of array)
      if(Array.isArray(el)) {
         yield "[";
         yield* asNested(el);
          yield "]";
      } else yield el.toString();
 }

 const result = [...asNested([[1, 2], [3, 4]])].join("");

2 Comments

This seems unnecessarily complicated compared to the above approach, and seems like it would use more time and computer resources, this is essentially the approach is said I wouldn't like in my question.
More complicated, yes, not necessarily slower.

Your Answer

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