Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array or string to array in JavaScript? [duplicate]

in my javascript program I have a function (not in my reach to edit) that returns a string or an array.

So I either have the output "one" or ["one", "two"]

I would like the output to alway be an array, so if it returns one string "one" I would like to have it as ["one"].

What is the most easy way to do this? (Preferably without an if)

I tried:

var arr = aFunction().split();

But when it does return an array, this won't work.

like image 762
moffeltje Avatar asked Nov 28 '15 14:11

moffeltje


2 Answers

EDIT:

As @Jaromanda X pointed out in the other answer you can use concat:

var result = [].concat(aFunction());

kudos!


I don't think there is a way to do this without an if, so just check if the output is a String and, in case, add it to an empty array.

var result = myFn();
if (typeof result === 'string' || result instanceof String) {
    result = new Array(result);
}
like image 83
Enrichman Avatar answered Sep 21 '22 12:09

Enrichman


use array concat function

var arr = [].concat(aFunction());
like image 36
Jaromanda X Avatar answered Sep 21 '22 12:09

Jaromanda X