Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added '_.ensureArray' function #816

wants to merge 1 commit into from


Copy link

commented Oct 7, 2012

This pull request adds a _.ensureArray utility function, which we frequently found ourselves mixin into underscore. As the name implies, it helps when you want to feed a perhaps-array value into an API that expects an array:

// arrays are passed straight through
_.ensureArray([1,2,3]); // => [1,2,3]

// non-array truthy values are wrapped in an array
_.ensureArray({a:1,b:2}); // => [{a:1,b:2}]
_.ensureArray("foo"); // => ["foo"]
_.ensureArray(432); // => [432]

// falsy values result in an empty array
_.ensureArray(null); // => []

Semantically we are perhaps treading a bit too far into the land of _.toArray here, but the functions behave very differently since toArray always treats the argument as a collection. For the above use cases, here is what toArray returns:

_.toArray([1,2,3]); // => cloned array [1,2,3]
_.toArray({a:1,b:2}); // => [1,2]
_.toArray("foo"); // => ["f","o","o"]
_.toArray(432); // => []

Only for falsy values do the two functions act the same.


This comment has been minimized.

Copy link

commented Oct 7, 2012

[].concat(X) is shorter and doesn't require underscore.


This comment has been minimized.

Copy link

commented Oct 7, 2012

[].concat(x) comes frustratingly close to solve the use case, but since [].concat(undefinedvar) === [undefined] it isn't usable. If the value is undefined we don't want to make the concatenation, and thus we have to do the code branching that _.ensureArray sets out to eliminate.


This comment has been minimized.

Copy link

commented Oct 20, 2012

Interesting, but way too special-case for Underscore. There are many situations where an API expects a particular type of object (that may or may not be coerceable from your input) ... and Arrays aren't the only type in town.

@jashkenas jashkenas closed this Oct 20, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
3 participants
You can’t perform that action at this time.