Skip to content

Instantly share code, notes, and snippets.

@albertojacini
Created June 28, 2014 14:15
Show Gist options
  • Save albertojacini/0d28e9d8f2f9724b34cb to your computer and use it in GitHub Desktop.
Save albertojacini/0d28e9d8f2f9724b34cb to your computer and use it in GitHub Desktop.
Angular groupBy filter
/*
* Inspired by http://stackoverflow.com/a/20645945
*/
app.filter('groupBy', ['$parse', function ($parse) {
return function (list, group_by) {
function addChangedTag (item, field) {
item[field + '_CHANGED'] = true;
}
var filtered = [];
var prev_item = null;
// loop through each item in the list
angular.forEach(list, function (item) {
// if not the first item
if (prev_item !== null) {
// check if any of the group by field changed
//force group_by into Array
group_by = angular.isArray(group_by) ? group_by : [group_by];
//check each group by parameter
for (var i = 0, len = group_by.length; i < len; i++) {
if ($parse(group_by[i])(prev_item) !== $parse(group_by[i])(item)) {
addChangedTag(item, group_by[i]);
}
}
}// otherwise we have the first item in the list which is new
else {
for (var i = 0, len = group_by.length; i < len; i++) {
addChangedTag(item, group_by[i]);
}
}
filtered.push(item);
prev_item = item;
});
return filtered;
};
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment