TimPetricola
TimPetricola

Reputation: 1491

Get array from variable in javascript

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"]

Upvotes: 0

Views: 56

Answers (3)

the system
the system

Reputation: 9336

Just use .concat().

[].concat("test");   // ["test"]
[].concat(["test"]); // ["test"]

Arrays will be flattened into the new Array. Anything else will simply be added.

Upvotes: 2

SeanCannon
SeanCannon

Reputation: 77966

I believe you can slice it:

var fooObj = {0: 123, 1: 'bar', length: 2};
var fooArr = Array.prototype.slice.call(fooObj);

Demo: http://jsfiddle.net/sh5R9/

Upvotes: 0

adeneo
adeneo

Reputation: 318212

function toArray(o) {
  return Array.isArray(o) ? o.slice() : [o];
};

Upvotes: 1

Related Questions