23

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.

cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • 3
    I don't believe there is casting in JavaScript. – Oded Oct 27 '12 at 18:25
  • There is casting in JS but it is seldom used (just like in PHP). A common use is to treat a number as a string or a string as a number. "1" + "1" = "11" if you are not careful. – Levi Botelho Oct 27 '12 at 18:29
  • 1
    You want to make it an Array of what? Should it be an Array of individual characters in the string? Or an Array that has the entire string at its first index? – I Hate Lazy Oct 27 '12 at 18:34

12 Answers12

41

Hacky, but works:

[].concat(arrayOrString);

//Usage:
[].concat("a");
//["a"]
[].concat(["a"]);
//["a"]
Pedro Nascimento
  • 13,136
  • 4
  • 36
  • 64
  • 3
    [Note] This is rather slow compared to the alternative: http://jsperf.com/array-coerce – Metalstorm Jan 23 '14 at 13:39
  • @Metalstorm Was it used in the same way? jsperf is currently down and I cannot check. – jeromej Jul 01 '15 at 03:17
  • @JeromeJ yes, it compares `concat` with `Array.isArray()`. The difference is noticeable. – Enrico Sep 14 '15 at 15:26
  • 1
    @Zim Ah thanks! Way faster indeed but sadly less beautiful: `Array.isArray(obj) ? obj:[obj]` – jeromej Sep 14 '15 at 18:00
  • This was the only solution I could find that would allow me to transform a string property to array inside a foreach statement. `([].concat(foo.bar.stringOrArray)).forEach((item) => {...})` – Kerry Johnson Jun 18 '22 at 18:25
29

JavaScript is a prototyping language and does not have a type casting system.

One solution would be to check if your variable is a string and convert it into an array. For example :

if (typeof someVariable === 'string') someVariable = [someVariable];

In PHP, if you do a check on a string, like (ex: $array = 'string';) :

$array = (array) $array;  // ex: "string" becomes array("string")

The JavaScript equivalent will be

arr = typeof arr === 'string' ? [arr] : arr;

If your variable arr is not necessarily a string, you may use instanceof (edit: or Array.isArray) :

arr = arr instanceof Array ? arr : [arr];
arr = Array.isArray(arr) ? arr : [arr];
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
7
var str    = "string";
var array  = str.split('');

console.log(array); // ['s', 't', 'r', 'i','n','g']
Andre Meinhold
  • 5,087
  • 3
  • 21
  • 29
4

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
Val
  • 17,336
  • 23
  • 95
  • 144
3

Turn a string into an array:

var myString = "['boop','top','foo']";
var myArray = JSON.parse(myString)
Don P
  • 60,113
  • 114
  • 300
  • 432
1

Just do like this

"sample".split("");

and you'll get

["s", "a", "m", ...]
vyakhir
  • 1,714
  • 2
  • 17
  • 21
  • If you have something like: "[10,20,34,0]" and you want it to be: [10,20,34,0], your solution won't work. – jartaud May 03 '18 at 19:53
0

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;
J. K.
  • 8,268
  • 1
  • 36
  • 35
  • How does it compare with `Array.isArray(str) ? str:[str]`? – jeromej Sep 14 '15 at 18:08
  • 1
    **Update:** http://stackoverflow.com/questions/22289727/difference-between-using-array-isarray-and-instanceof-array > `Array.isArray` is a bit better. – jeromej Sep 14 '15 at 18:14
0
"1,2,3".split(",") 
=> ["1", "2", "3"]

use split()

AnandVeeramani
  • 1,526
  • 9
  • 15
0

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
Rahul
  • 1
  • 1
0

You can also use the following if statement:

if(array instanceof Array != true) {array = [array];}
jcwhall
  • 63
  • 4
0
Array.isArray(foo) || (foo = [foo]);

or if that's not comfortable

foo = Array.isArray(foo) ? foo : [foo];
grantwparks
  • 1,124
  • 9
  • 13
-2

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']
Philipp Kühn
  • 1,579
  • 2
  • 16
  • 25