6

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.

cweiske
  • 30,033
  • 14
  • 133
  • 194
moffeltje
  • 4,521
  • 4
  • 33
  • 57

3 Answers3

8

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);
}
Community
  • 1
  • 1
Enrichman
  • 11,157
  • 11
  • 67
  • 101
4

use array concat function

var arr = [].concat(aFunction());
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
-1

Without "if" ;) (but internally the ternary operator is doing the if / else stuff)

var result = aFunction();
result = (typeof result == "string") ? [result] : result;
webdeb
  • 12,993
  • 5
  • 28
  • 44