0

Array:

myArr = [[1, 2, 3], [4, 5, 6]]

Expected output:

newArr = "[[1, 2, 3], [4, 5, 6]]"

I have tried:

myArr.toString()
String(myArr)
myArr = `${myArr}`

What I got by doing the above methods:

'1,2,3,4,5,6'
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Possible duplicate of this : https://stackoverflow.com/questions/22746353/javascript-convert-array-to-string-while-preserving-brackets – Kushagra Sharma Aug 16 '22 at 04:52

3 Answers3

3

I gather what you would like to achieve is more or less serialization. We could use JSON.stringify in JavaScript to serialize an Array.

const array = [[1, 2, 3], [4, 5, 6]];
const serializedArray = JSON.stringify(arr));

To deserialize the Array, JSON.parse could be used.

const originalArray = JSON.parse(serializedArray));
Preet Mishra
  • 389
  • 3
  • 7
1

JSON.strinify is what you need. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

const myArr = [[1, 2, 3], [4, 5, 6]];
const myArrString = JSON.stringify(myArr);

console.log(`Here is my string: ${myArrString}`);
davidhu
  • 9,523
  • 6
  • 32
  • 53
0

use JSON.stringify(myArr);

you can find out more on below link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

SalunkeAkash
  • 236
  • 1
  • 9