Created
April 17, 2014 10:31
-
-
Save mrzmyr/10972141 to your computer and use it in GitHub Desktop.
AngularJS – groupBy filter
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
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; | |
} | |
}; | |
}); |
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
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