Skip to content

Instantly share code, notes, and snippets.

@ifandelse
Created April 5, 2012 15:54
Show Gist options
  • Select an option

  • Save ifandelse/2312088 to your computer and use it in GitHub Desktop.

Select an option

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
_.mixin({
groupsOf: function(list, num) {
if (!_.isArray(list)) {
list = _.toArray(list);
}
var result = [];
while (list.length) {
result.push(list.splice(0, num));
}
return result;
}
});
_.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