Skip to content

Instantly share code, notes, and snippets.

@mrzmyr
Created April 17, 2014 10:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrzmyr/10972141 to your computer and use it in GitHub Desktop.
Save mrzmyr/10972141 to your computer and use it in GitHub Desktop.
AngularJS – groupBy filter
angular.module('filters.groupBy', [])
.filter('groupBy', function() {
return function(items, groupedBy) {
if (items) {
var finalItems = [],
thisGroup;
for (var i = 0; i < items.length; i++) {
if (!thisGroup) {
thisGroup = [];
}
thisGroup.push(items[i]);
if (((i+1) % groupedBy) === 0) {
finalItems.push(thisGroup);
thisGroup = null;
}
}
if (thisGroup) {
finalItems.push(thisGroup);
}
return finalItems;
}
};
});
describe('filter groupBy', function () {
beforeEach(module('filters.groupBy'));
it('should group an array', inject(function(groupByFilter) {
expect(groupByFilter([1,2,3,4,5], 2)).toEqual([[1,2], [3,4], [5]]);
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment