0

I have problem in sorting an array of objects

The object looks like

enter image description here

All I want is to make the *ngFor loop sort it by the group_id property.

component.html

<ul *ngFor="let list of selectgid | groupid">
  <li>{{list}}</li>
</ul>

pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'groupid'
 })
export class GroupidPipe implements PipeTransform {

transform(array: Array<any>): Array<any> {
  if (array !== undefined) {
  array.sort((a: any, b: any) => {
    if (a.group_id < b.group_id) {
      return -1;
    } else if (a.group_id > b.group_id) {
      return 1;
    } else {
      return 0;
    }
  });
}
  return array;
}
}

I tried to implement this code but it doesn't seem to working. What is wrong in my code or is there anything that needs to be done?

Jijo Robin
  • 365
  • 9
  • 27
  • Do you specifically want this sort to be a pipe? Is `selectgid` an array or an observable array? – P. Moloney Nov 22 '18 at 06:04
  • Take a search through stackoverflow; there are plenty questions around this: [Async Pipe Sort](https://stackoverflow.com/questions/35928432/implementing-an-asynchronous-sorting-pipe-in-angular-2), [Regular Pipe Sort](https://stackoverflow.com/questions/50969262/angular-pipe-sorting) – P. Moloney Nov 22 '18 at 06:06
  • It is not recommended by the Angular team to do it like this though, see [Angular Docs- Filtering Pipe](https://stackoverflow.com/questions/50969262/angular-pipe-sorting) – P. Moloney Nov 22 '18 at 06:07

1 Answers1

0

Assuming selectgid is your array of object containing the values shown in the image try to sort your data inside ngOnInit() method in your .ts file like this:

this.selectgid.sort((a, b) => {
    if (a.group_id < b.group_id) {
        return -1;
    } else if (a.group_id > b.group_id) {
        return 1;
    } else {
        return 0;
    }
})

And on .html page you need to specify the key of Object like this:

<ul *ngFor="let list of selectgid">
    <li>{{list.group_id}}</li>
    <li>{{list.permission_list}}</li>
</ul>