How to convert a table or string to an array in JavaScript?

advertisements

This question already has an answer here:

  • Check if object is array? 36 answers

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.


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);
}