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);
}
use array concat function
var arr = [].concat(aFunction());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With