Created
November 19, 2012 03:22
-
-
Save aaronpowell/4108776 to your computer and use it in GitHub Desktop.
LINQ SelectMany in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)