0

Suppose I have an array like this:

var bestArray = ["Veni", "vidi", "vici"];

Now, I use the method toString () in order to traduce the array to a string like this:

var bestString = bestArray.toString(); // "Veni, vidi, vici"

Here, my code works fine. But, now I want to traduce bestString to an array. How can I achieve this?

SphynxTech
  • 1,719
  • 2
  • 17
  • 35

3 Answers3

3

You should use Array.join and Arrat.split instead:

var bestArray = ["Veni", "vidi", "vici"];

var joined = bestArray.join(",");
console.log(joined);

var split = joined.split(",");
console.log(split);

Note: Array.split will give you incorrect results if your source array has elements containing a comma (,).

So, if you do not plan to represent the array string to a GUI, you should use JSON.stringify and JSON.parse.

Nisarg Shah
  • 13,626
  • 5
  • 36
  • 53
1

Use .split(,)

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

var bestArray = ["Veni", "vidi", "vici"];
var sArray = bestArray.toString();
console.log(sArray);

var arrayAgain = sArray.split(",");
console.log(arrayAgain);
void
  • 34,922
  • 8
  • 55
  • 102
1

Split it by comma ,

["Veni", "vidi", "vici"].toString().split(","); 

output is ["Veni", "vidi", "vici"] again.

Demo

["Veni", "vidi", "vici"].toString().split(","); 

var inputArr = ["Veni", "vidi", "vici"];

console.log( "toString ", inputArr.toString() ) ;

console.log( "back to array ", inputArr.toString().split(",") ) ;
gurvinder372
  • 64,240
  • 8
  • 67
  • 88