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,799
  • 2
  • 18
  • 38

3 Answers3

4

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
  • 14,151
  • 6
  • 34
  • 55
2

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
  • 66,980
  • 10
  • 72
  • 94
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
  • 36,090
  • 8
  • 62
  • 107