What's the underscore.js equivalent to LINQ's SelectMany operator?

Drew Noakes picture Drew Noakes · Sep 10, 2012 · Viewed 13.1k times · Source

Imagine I have a nested array structure.

var nested = [ [1], [2], [3] ];

Using underscore.js, how would I produce a flattened array?

In C# you would use Enumerable.SelectMany like this:

var flattened = nested.SelectMany(item => item);

Note that the lambda in this case selects the nested item directly, but it could have been any arbitrary expression.

In jQuery, it's possible to just use:

var flattened = $.map(nested, function(item) { return item; });

However this approach doesn't work with underscore's map function.

So how would I get the flattened array [1, 2, 3] using underscore.js?

Answer

armen.shimoon picture armen.shimoon · Sep 10, 2012
var nested = [ [1], [2], [3] ];
var flattened = _.flatten(nested);

Heres a fiddle