Home >Web Front-end >JS Tutorial >How can I group data by a property using Angular\'s `groupBy` filter?
Grouping Data with Angular Filters
In Angular applications, data grouping is a common task to organize large datasets. Using the groupBy filter, you can easily group your data by a specific property and display it in a structured manner.
Problem:
Imagine you have an array of players, each with a "team" property. You wish to display a list of players grouped by their teams.
[ { name: 'Gene', team: 'alpha' }, { name: 'George', team: 'beta' }, { name: 'Steve', team: 'gamma' }, { name: 'Paula', team: 'beta' }, { name: 'Scruath', team: 'gamma' }, ];
Desired Result:
team alpha - Gene team beta - George - Paula team gamma - Steve - Scruath
Solution:
$scope.players = [ { name: 'Gene', team: 'alpha' }, { name: 'George', team: 'beta' }, { name: 'Steve', team: 'gamma' }, { name: 'Paula', team: 'beta' }, { name: 'Scruath', team: 'gamma' }, ];
<ul ng-repeat="(key, value) in players | groupBy: 'team'"> <li>{{ key }}</li> <ul> <li ng-repeat="player in value">{{ player.name }}</li> </ul> </ul>
The groupBy filter takes a property name and groups the array elements by that property. In the above code, the players are grouped by their team property.
NOTE:
To use the groupBy filter, you must include the angular.filter dependency in your module and ensure that the angular-filter.js file is loaded in your application.
This powerful filter enables you to easily organize and display data in your Angular applications, providing a structured and intuitive user experience.
The above is the detailed content of How can I group data by a property using Angular\'s `groupBy` filter?. For more information, please follow other related articles on the PHP Chinese website!