Skip to content

Instantly share code, notes, and snippets.

@aaronpowell
Created November 19, 2012 03:22
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save aaronpowell/4108776 to your computer and use it in GitHub Desktop.
Save aaronpowell/4108776 to your computer and use it in GitHub Desktop.
LINQ SelectMany in JavaScript
Array.prototype.selectMany = function (fn) {
return this.map(fn).reduce(function (x, y) { return x.concat(y); }, []);
};
// usage
console.log([[1,2,3], [4,5,6]].selectMany(function (x) { return x; })); //[1,2,3,4,5,6]
console.log([{ a: [1,2,3] }, { a: [4,5,6] }].selectMany(function (x) { return x.a; }));
console.log([{ title: 'Some Blog', tags: ['being awesome'] }, { title: 'Some Other Blog', tags: ['still awesome', 'javascript'] } ].selectMany(function (blog) { return blog.tags; }));
@gerardpaapu
Copy link

I don't know if you're using this snippet, or if you've rewritten it since or whatever, but I think you can get better performance with concatting all the results at once, rather than using reduce (which creates an array per result).

I created a fork here: https://gist.github.com/sharkbrainguy/5086585
And a jsperf case here: http://jsperf.com/concatenating-many-arrays

It's faster for the use-case where you're returning many results per item for many items (in latest chrome, latest ff, and IE9).

I hope that's helpful :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment