Angular filter - organizing objects based on a specific property or a combination of properties

I modified the Angular filter group by example by converting the team into an object.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene', 
    team: {
      'id' : '1',
      'name' : 'alpha'
      
    }
  },
  {
    name: 'George', 
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve', 
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula', 
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath', 
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);
<!DOCTYPE html>
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0c030a18010c1f071e2d5c435b435f">[email protected]</a>" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ul>
        <li ng-repeat="(team, players) in players | groupBy: 'team.name'">
          <a href="#I need the team ID">Group name: {{ team }}</a>
          <ul>
            <li ng-repeat="player in players">
              player: {{ player.name }}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </body>

</html>

However, if I require the team id in the group by, what should I do?

<a href="#I need the team ID">Group name: {{ team }}</a>

I attempted to group by the team object using team.name and team.id, but it was unsuccessful. Additionally, I struggled with creating a group by with multiple fields like (team.id, team.name)

Here's a functional plnkr

Answer №1

My solution is quite straightforward:

I decided to group by the identifier team.id

<li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">

Then, I utilized the expression: players[0].team.name within each group

<li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
    <a href="#I can reference the teamid for this group">Group name: {{ players[0].team.name }}</a>
      <ul>
        <li ng-repeat="player in players">
          player: {{ player.name }}
        </li>
     </ul>
</li>

Given that the players within each group are specifically the players affiliated with that particular team where they all share the same team, it follows that players[0], players[1], and so forth will possess the same team name.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene', 
    team: {
      'id' : '1',
      'name' : 'alpha'
      
    }
  },
  {
    name: 'George', 
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve', 
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula', 
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath', 
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);
<!DOCTYPE html>
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b5bab3a1b8b5a6bea794e5fae2fae6">[email protected]</a>" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ul>
        <li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
          <a href="#I can use the group's teamid here">Group name: {{ players[0].team.name }}</a>
          <ul>
            <li ng-repeat="player in players">
              player: {{ player.name }}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </body>

</html>

Answer №2

In order to ensure accurate data output, it is recommended to group by team.id rather than team name since team names may not be unique. To address this issue, you can pre-collect the teams in the controller and normalize them using team.id within a separate object. Here's a link to a demo fiddle showcasing this solution - demo fiddle:

View

<body ng-app="myApp">
<div ng-controller="MainController">
    <ul>
        <li ng-repeat="(team, players) in players | groupBy: 'team.id'">
            <a href="{{ team }} ">Group name: {{ teams[team].name }}</a>
            <ul>
                <li ng-repeat="player in players">
                    player: {{ player.name }}
                </li>
            </ul>
        </li>
    </ul>
</div>
</body>

AngularJS Application

var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){

    $scope.players = [
        {
            name: 'Gene',
            team: {
                'id' : '1',
                'name' : 'alpha'

            }
        }, {
            name: 'George',
            team: {
                'id' : '2',
                'name' : 'beta'
            }
        }, {
            name: 'Steve',
            team: {
                'id' : '3',
                'name' : 'gamma'
            }
        }, {
            name: 'Paula',
            team: {
                'id' : '4',
                'name' : 'beta'
            }
        }, {
            name: 'Scruath',
            team: {
                'id' : '5',
                'name' : 'gamma'
            }
        }];

    $scope.teams = {};

    $scope.players.forEach(function (player) {
        if (angular.isUndefined($scope.teams[player.team.id])) {
            $scope.teams[player.team.id] = player.team;
        }
    });
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Twitter Bootstrap Grid System Cell Divider

Currently, I have a bootstrap grid with one row and two columns, and I am looking to add a splitter between those columns. Below is how my code looks: <div class="container-fluid"> <div class="row"> <div class="col-md-6"> ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

Enhancing the ShaderMaterial attribute in three.js

Exploring the three.js tutorial on shaders, we discover a technique for updating uniform values of a ShaderMaterial: var attributes = { displacement: { type: 'f', // a float value: [] // an empty array } }; var uniforms = { amplitu ...

Nextjs is facing challenges in enhancing LCP specifically for text content

I've been trying to boost my LCP score by optimizing the text on my page, but it seems stuck and I can't figure out why my LCP isn't improving. Take a look at the screenshot: https://i.stack.imgur.com/xfAeL.png The report indicates that &a ...

What is the best way to extract row data from a datatable and transmit it in JSON format?

I have successfully created a code that retrieves data from a dynamic table using ajax. However, I am facing an issue where I only want to send data from checked rows. Despite trying different approaches, I keep encountering errors or receive an empty arra ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

Issue with ForwardRef component in Jest for React Native testing

When attempting to write a test case for my Post Detail screen, I encountered an error that stated: error occurred in the <ForwardRef> component: Here is my test class code: import React from "react"; import { NewPostScreenTemplate } from ...

Building a Slider component in a React class using Materialize CSS

I currently have a functioning slider implemented in a React function component. I am now looking to correctly integrate the slider below into a React class component. import * as React from 'react'; import Box from '@mui/material/Box'; ...

Determine whether a child node is an element or a text node using JavaScript

I am experiencing an issue with the childNodes property. Here is the scenario: <ol> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ol> //childNodes.length = 7 However, <ol><li> ...

The framework for structuring web applications using Javascript programming

While I have extensive experience in PHP and C# programming, my knowledge of Javascript is limited. When it comes to server side programming, MVC is my preferred method as it allows me to keep my code well-organized. However, when it comes to writing Java ...

Exploring the relationship between AngularJS and HTTP headers

I am trying to send a custom HTTP header to the REST service with every request I make. My setup involves using Apache HTTP Web Server, and below is the code snippet I have created: app.config(['$httpProvider', function($httpProvider){ if(!$ ...

Retrieve progress with easing using jQuery's animate() function

At the moment, I'm utilizing this code to create an animation for a bar-graph-inspired element: $('.anim').animate({ right: `${100-(e/max*100)}%`, backgroundColor: colors[0] },{ duration: 1500, easing: 'easeInQuart&apos ...

What is the best way to create a function that triggers another function every minute?

Currently, I have a function that checks if a user is authenticated: isAuthenticated = (): boolean => { xxx }; I am working with AngularJS and I want to create a new function called keepCheckingAuthentication() This new function should call the ...

Error: Unable to access property 'camera' as it is undefined

After implementing the Raycaster from Three js to detect collision following a MouseMove event, I encountered an error: Cannot read properties of undefined (reading 'camera') Here is the code snippet causing the issue: bindIFrameMousemove(if ...

What is the process for converting monthly data into an array?

I am working with an array of daily data that looks like this: var data = [{x: '2017-01-01', y: 100}, {x: '2017-01-02', y: 99}, /* entire year. */]; Each element in the array has an x field for date and a y field for a number. This ar ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

Creating a triangle number pattern in JavaScript with a loop

Hi there, I'm currently facing an issue. I am trying to generate a triangular number pattern like the one shown below: Output: 1223334444333221 =22333444433322= ===3334444333=== ======4444====== I attempted to write a program for this, however, ...

Receiving the message "servlet temporarily moved" while attempting to pass serializable data through an AJAX request to a servlet

Here is the code snippet I am using to send serializable data on an ajax call to a servlet: $.ajax({ type: "post", url: registersubmit.RegisterServlet.json, dataType: "json", data:$('#registrationForm').serialize(), ...

Tips for optimizing the page speed of your Pixi JS app by ensuring it runs efficiently after the page loads

On my website, I implemented a dynamic gradient animation with shape-changing blobs using pixi js. The animation functions flawlessly, but the issue arises when I run page speed tests - the test assumes that the page has not finished rendering because the ...

What is the method used by Vue.js to establish observers in computed properties?

Consider this scenario: computed: { greeting() { const state = this.$store.state; if (state.name === 'Joe') { return 'Hey, Joe'; } else { return 'Hello, ' + state.name; } } } Which object(s) w ...