0

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"]
2
  • Your example uses an string, not an object. Your question says "if it's not already [an array]" but returns a new array regardless. What do you really want? Commented Mar 5, 2013 at 1:20
  • It could be whatever that it's not an array: object, string, integer, ... Commented Mar 5, 2013 at 1:24

3 Answers 3

2

Just use .concat().

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

Yeah it would work but it's actually exactly the same code, just written as a ternary. I'm looking for something else, like a single method. But I actually doubt it exists :)
You're not really converting an object to an array, it looks like you're just returning a new array both if it's already an array and if it's a string, so I don't think there is a built in function that does both without some type checking and two different methods, like above.
Yep you're right, I'm not really converting it. I edited the question to make it more clear. Thanks :)
From some of the answers it seems you can just join it with an existing array using concat(), and create an array, regardless of wether or not it's a string or array, so that's neat, even if it does pretty much the same thing.
Yeah I accepted the concat() way. No need for a new function with it
0

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/

3 Comments

you cannot. in chrome at least not.
For numeric keys, sure -- { 0: 123, 1: 'bar', length: 2 }. But, I think the OP is after Array-wrapping more than direct conversion.
It's not really what I'm looking for. I want to put the object as the first entry of an array (if it's not already one). So the expected result with your object would be: [{0: 123, 1: 'bar', length: 2}]. But it's nice to know that you can call slice on an object!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.