Home > Web Front-end > JS Tutorial > How can I group data by a property using Angular\'s `groupBy` filter?

How can I group data by a property using Angular\'s `groupBy` filter?

Linda Hamilton
Release: 2024-11-17 12:21:02
Original
751 people have browsed it

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' },
];
Copy after login

Desired Result:

team alpha
 - Gene

team beta
 - George
 - Paula

team gamma
 - Steve
 - Scruath
Copy after login

Solution:

$scope.players = [
  { name: 'Gene', team: 'alpha' },
  { name: 'George', team: 'beta' },
  { name: 'Steve', team: 'gamma' },
  { name: 'Paula', team: 'beta' },
  { name: 'Scruath', team: 'gamma' },
];
Copy after login
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
  <li>{{ key }}</li>
  <ul>
    <li ng-repeat="player in value">{{ player.name }}</li>
  </ul>
</ul>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template