Created
April 5, 2012 15:54
-
-
Save ifandelse/2312088 to your computer and use it in GitHub Desktop.
Underscore mixin that takes a list and splits it into multiple lists, where each list is n elements long
This file contains hidden or 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
| _.mixin({ | |
| groupsOf: function(list, num) { | |
| if (!_.isArray(list)) { | |
| list = _.toArray(list); | |
| } | |
| var result = []; | |
| while (list.length) { | |
| result.push(list.splice(0, num)); | |
| } | |
| return result; | |
| } | |
| }); |
This file contains hidden or 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
| _.groupsOf([1, 2, 3, 4, 5, 6, 7], 3); // returns [ [1,2,3], [4,5,6], [7] ] | |
| _.groupsOf({ | |
| valA: { | |
| firstName: "George", | |
| lastName: "Washington" | |
| }, | |
| valB: { | |
| firstName: "John", | |
| lastName: "Adams" | |
| }, | |
| valC: { | |
| firstName: "Thomas", | |
| lastName: "Jefferson" | |
| }, | |
| valD: { | |
| firstName: "Aaron", | |
| lastName: "Burr" | |
| }, | |
| valE: { | |
| firstName: "James", | |
| lastName: "Madison" | |
| }, | |
| valF: { | |
| firstName: "George", | |
| lastName: "Clinton" | |
| }, | |
| valG: { | |
| firstName: "James", | |
| lastName: "Monroe" | |
| }, | |
| valH: { | |
| firstName: "Daniel", | |
| lastName: "Tompkins" | |
| } | |
| }, 2); | |
| /* | |
| above function call returns: | |
| [ | |
| [{"firstName":"George","lastName":"Washington"},{"firstName":"John","lastName":"Adams"}], | |
| [{"firstName":"Thomas","lastName":"Jefferson"},{"firstName":"Aaron","lastName":"Burr"}], | |
| [{"firstName":"James","lastName":"Madison"},{"firstName":"George","lastName":"Clinton"}], | |
| [{"firstName":"James","lastName":"Monroe"},{"firstName":"Daniel","lastName":"Tompkins"}] | |
| ] | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment