Home > Software design >  Filter results if they have a group set
Filter results if they have a group set

Time:02-16

I have a list of service users with IDs that I want to filter out from the search list if they already exist in a group table.

There are 2 tables involved - firstly 'group-user' - that includes groupId & serviceUserId, the second table is 'group' and it has the groupId & groupName.

When the addUserToGroupModal function is called, I want to display only names that have no group assigned.

onInIt the listGroups function is called to get all groups and users within the group -

async listGroups() {
 await Promise.all([
  this.groupService.getGroups(true).then((result) => (this.groups = [...result])),
  this.userService.getActiveAndInHospitalServiceUsers(false).then((result) => (this.serviceUsers = [...result])),
  this.groupService.getGroupUsers(true).then((result) => (this.groupUsers = [...result]))
]).then(() => {
  this.groupMap.clear();
  this.groupIdMap.clear();
  this.groups.forEach((group) => {
    const idsForUsersInGroup = this.groupUsers.filter((groupUser) => groupUser.groupId === group.id).map((groupUser) => groupUser.serviceUserId);
    const usersInGroup = this.serviceUsers.filter((serviceUser) => idsForUsersInGroup.includes(serviceUser.id));
    this.groupIdMap.set(group.id, group.name);
    this.groupMap.set(group.name, {id: group.id, users: usersInGroup});
  });
 });
}

When the modal function is called I need the filter to be applied to only show serviceUsers that do not have a group.

async addUserToGroupModal(template: TemplateRef<any>) {
  this.addUserRef = this.modalService.show(template, {class: 'modal-lg', backdrop: 'static', keyboard: false});
}

I'm using a datalist to display the users -

<datalist id="groupSelect">
    <option *ngFor="let serviceUser of serviceUsers"
            [value]="serviceUser.id"
    >
      {{serviceUser.firstName}} {{serviceUser.lastName}}
  </datalist>

CodePudding user response:

You can add an extra variable usersWithAGroup that memorize all the users actually assigned to a group :

let usersWithAGroup = [];
this.groups.forEach((group) => {
  const idsForUsersInGroup = this.groupUsers.filter((groupUser) => groupUser.groupId === group.id).map((groupUser) => groupUser.serviceUserId);
  Array.prototype.push.apply(usersWithAGroup, idsForUsersInGroup );
  const usersInGroup = this.serviceUsers.filter((serviceUser) => idsForUsersInGroup.includes(serviceUser.id));
  this.groupIdMap.set(group.id, group.name);
  this.groupMap.set(group.name, {id: group.id, users: usersInGroup});
});

Then in your html, you filter if the user is not present in usersWithAGroup :

<datalist id="groupSelect">
  <option *ngFor="let serviceUser of serviceUsers"
        [value]="serviceUser.id">
  <span *ngIf="!usersWithAGroup.includes(serviceUser.id)">{{serviceUser.firstName}} {{serviceUser.lastName}}</span>
</datalist>
  • Related