Drew Noakes Drew Noakes - 1 year ago 186
Javascript Question

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

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
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 Source
var nested = [ [1], [2], [3] ];
var flattened = _.flatten(nested);

Heres a fiddle