I'm looking to get an array from a variable. If it's not already an array I want to return a new array with the variable as the only entry.Example:
toArray('test'); // => ["test"]
toArray(['test']); // => ["test"]
My actual working code is:
var toArray;
toArray = function(o) {
if (Array.isArray(o)) {
return o.slice();
} else {
return [o];
}
};
I'd like to know if there is a nicer way for that (native or with underscore.js for example).
In ruby, you can do:
Array('test') # => ["test"]
Array(['test']) # => ["test"]