25

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.

Answer - Using the selected answer with the more recent Array.flat() we can do:

let foo = 'foo'
let bar = ['foo']

[foo].flat() // ['foo']
[bar].flat() // ['foo']

It does require wrapping in brackets but does cast as array only if necessary in one go without ternary.

3
  • 3
    I don't believe there is casting in JavaScript. Commented Oct 27, 2012 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. Commented Oct 27, 2012 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? Commented Oct 27, 2012 at 18:34

13 Answers 13

42

Hacky, but works:

[].concat(arrayOrString);

//Usage:
[].concat("a");
//["a"]
[].concat(["a"]);
//["a"]
Sign up to request clarification or add additional context in comments.

5 Comments

[Note] This is rather slow compared to the alternative: jsperf.com/array-coerce
@Metalstorm Was it used in the same way? jsperf is currently down and I cannot check.
@JeromeJ yes, it compares concat with Array.isArray(). The difference is noticeable.
@Zim Ah thanks! Way faster indeed but sadly less beautiful: Array.isArray(obj) ? obj:[obj]
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) => {...})
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];

Comments

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

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

4 Comments

in PHP doing str = (array)"string" results in array("string") not array('s','t','r','i','n','g').
Any way I was looking for ['s', 't', 'r', 'i','n','g'] from "string". THX
str_split($my_string) in PHP btw.
If that's what you want (and not what the OP was asking for), then just use Array.from() see MDN notes [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
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

1 Comment

You don't need jQuery for that (Any more) , JSON.parse(arr); works the same.
3

Turn a string into an array:

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

Comments

1

Modern JavaScript now has Array.prototype.flat() which will do the trick.

let a = "a";
let b = "b";

[a].flat(); // result: ["a"]
[[a, b]].flat(); // result ["a", "b"]

This allows you to do this in your function:

function acceptsArrayOrScalar(arrayOrScalar){
   return [arrayOrScalar].flat();
}

acceptsArrayOrScalar(a); // returns [a]
acceptsArrayOrScalar([a, b]); // returns [a, b]

This kind of thing is useful if you want to be able to iterate over your parameter with a for..of or forEach and you don't want to have to do a manual check of isArray() etc.

function doStuff(param){
   [param].flat().forEach(x => console.log(x));
}

doStuff("a"); // logs "a"
doStuff(["a", "b"]); // logs "a" and then "b"

In the contrived example above, you could probably achieve a similar result with the ...rest parameter if all you care about is being able to handle a variable amount of parameters:

function doMoreStuff(...param){
   param.forEach(x => console.log(x));
}

Note though that in this last example, we're not accepting a scalar or an array, we're accepting a variable number of arguments, so it's a slightly different signature, but it might be just what you need.

doMoreStuff("a"); // logs "a"
doMoreStuff("a", "b"); // logs "a" and then logs "b"
doMoreStuff(["a", "b"]); // maybe not what we want: logs ["a", "b"]

And if you want real versatility where you can accept a scalar, or an array, or a variable number of scalars, you could specify the depth parameter:

function doAllTheStuff(...params){
   [params].flat(2).forEach(x => console.log(x));
}

doAllTheStuff("a"); // logs "a"
doAllTheStuff(["a", "b"]); // logs "a" and then "b"
doAllTheStuff("a", "b", "c"); // logs "a", then "b", then "c"

...and even...

doAllTheStuff(["a", "b"], "c"); // logs "a", then "b", then "c"

Arguably, the Array.isArray() ternary is computationally faster, it's unlikely that any production code that uses this trick will suffer significantly, but just be aware of that nuance if inside a game loop or something that needs to be highly performant.

2 Comments

13 years later I think its time to pick an answer and that's prob as close as we're going to get.
Appreciate it @cyberwombat :)
1

Just do like this

"sample".split("");

and you'll get

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

1 Comment

If you have something like: "[10,20,34,0]" and you want it to be: [10,20,34,0], your solution won't work.
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;

2 Comments

How does it compare with Array.isArray(str) ? str:[str]?
Update: stackoverflow.com/questions/22289727/… > Array.isArray is a bit better.
0
"1,2,3".split(",") 
=> ["1", "2", "3"]

use split()

1 Comment

this is not the PHP equivalent asked in the question
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

Comments

0

You can also use the following if statement:

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

Comments

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

or if that's not comfortable

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

Comments

-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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.