Home >Web Front-end >JS Tutorial >How can I group data by a specific property in Angular?
In the realm of Angular applications, efficiently organizing and displaying complex data sets is crucial. One effective approach is to group data based on specific criteria, enabling users to navigate and comprehend the information effortlessly.
Suppose you have a list of players who belong to various teams. Your task is to present this data in a structured manner, listing the players within their respective teams. For example:
Players List:
[ {name: 'Gene', team: 'team alpha'}, {name: 'George', team: 'team beta'}, {name: 'Steve', team: 'team gamma'}, {name: 'Paula', team: 'team beta'}, {name: 'Scruath of the 5th sector', team: 'team gamma'} ]
Desired Result:
- team alpha - Gene - team beta - George - Paula - team gamma - Steve - Scruath of the 5th sector
Angular provides an invaluable filter named groupBy that empowers you to effortlessly group data based on specified properties. By leveraging this filter, you can achieve the desired result in a straightforward manner.
JavaScript Code:
$scope.players = [ {name: 'Gene', team: 'alpha'}, {name: 'George', team: 'beta'}, {name: 'Steve', team: 'gamma'}, {name: 'Paula', team: 'beta'}, {name: 'Scruath', team: 'gamma'} ];
HTML Template:
<ul ng-repeat="(key, value) in players | groupBy: 'team'"> Group name: {{ key }} <li ng-repeat="player in value"> player: {{ player.name }} </li> </ul>
When you execute the code, you will obtain the following output:
Group name: alpha * player: Gene Group name: beta * player: George * player: Paula Group name: gamma * player: Steve * player: Scruath
As you can observe, the players are now grouped according to their teams, providing a far more organized and user-friendly data representation.
To fully capitalize on the utility of angular.filter, remember the following crucial steps:
The above is the detailed content of How can I group data by a specific property in Angular?. For more information, please follow other related articles on the PHP Chinese website!