I am working with the following object and need to create a filter to group data by ParentCategoryID.
[
{id : 116, Desciption : 'Item1', ParentID : 1, parent : 'Parent1'},
{id : 117, Desciption : 'Item2', ParentID : 2, parent : 'Parent2'},
{id : 118, Desciption : 'Item3', ParentID : 2, parent : 'Parent2'},
{id : 119, Desciption : 'Item4', ParentID : 1, parent : 'Parent1'}
]
The desired outcome is:
Parent1
Item1
Item4
Parent2
Item2
Item3
The current state of my filter is as follows:
productDetailsApp.filter('groupBy', function() {
return function(list, group_by) {
var filtered = [];
var prev_item = null;
angular.forEach(list, function(item) {
if (prev_item !== null) {
if (prev_item[group_by] === item[group_by]) {
filtered.push(item);
}
}
prev_item = item;
});
console.log(filtered);
return filtered;
};
});
And in the HTML :
<div data-ng-repeat="d in details | groupBy:'ParentID'">
<h2 >{{d.parent}}</h2>
<li>{{d.Desciption}}</li>
</div>
However, this only displays the last element as prev_item for the first item will always be null:
Parent1
Item4
Parent2
Item3
If anyone can provide assistance, I would greatly appreciate it. Thank you.