'Cast string as array

How, in Javascript, can I cast a string as an array in the same way that PHP (array) does.

//PHP
$array = (array)"string"

Basically I have a variable that can be an array or a string and, if a string, I want to make it an array using an inline command.



Solution 1:[1]

Hacky, but works:

[].concat(arrayOrString);

//Usage:
[].concat("a");
//["a"]
[].concat(["a"]);
//["a"]

Solution 2:[2]

var str    = "string";
var array  = str.split('');

console.log(array); // ['s', 't', 'r', 'i','n','g']

Solution 3:[3]

You can in jQuery...

var arr = "[1,2,3,4,5]"; 
window.x = $.parseJSON(arr);
console.log(x);//cast as an array...

it works even if you have something like

[{"key":"value"}]

However this may NOT work if you have something like this...

[{key:"value"}] // different is the " (double quotes) on key

Solution 4:[4]

Turn a string into an array:

var myString = "['boop','top','foo']";
var myArray = JSON.parse(myString)

Solution 5:[5]

Just do like this

"sample".split("");

and you'll get

["s", "a", "m", ...]

Solution 6:[6]

You cannot cast to Array in JS but a simple ternary operation can do what you want.

var str = 'string';
var arr = (str instanceof Array) ? str : [ str ];

This works for any non-Array object or any primitive value. If you're sure that only actual Array objects and string primitives can be encountered here, the following is a bit faster:

var arr = (typeof str === 'string') ? [ str ] : str;

Solution 7:[7]

"1,2,3".split(",") 
=> ["1", "2", "3"]

use split()

Solution 8:[8]

Val's suggestion also works for strings which have array of arrays

var str = "[[1121,1],[1122,2],[1123,3]]";
var arr = $.parseJSON(str);
console.log(arr); //returns array of arrays

Solution 9:[9]

You can also use the following if statement:

if(array instanceof Array != true) {array = [array];}

Solution 10:[10]

Array.isArray(foo) || (foo = [foo]);

or if that's not comfortable

foo = Array.isArray(foo) ? foo : [foo];

Solution 11:[11]

There is already a proposal for Array.flatten() and usable with babel-preset-stage-2.

const array = ['foo'].flatten()
console.log(array) // ['foo']

const array = [['foo', 'bar']].flatten()
console.log(array) // ['foo', 'bar']