How go get *ngFor loop unique records

2020-04-07 19:07发布

问题:

How to get unique records from this array. I need to get unique {{ subitem.author }} from this array of items.

<div *ngFor="let item of items">   
    <ion-list *ngFor="let subitem of item.items" (click)="authorquotes(subitem.author);">
        <ion-item >
            {{ subitem.author }} 
        </ion-item>
    </ion-list>
</div> 

In array having multiple records. From that array, I need to filter unique authors.

回答1:

You have to create a pipe that filters the array with unique items:

@Pipe({
  name: 'filterUnique',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    // Remove the duplicate elements
    let uniqueArray = value.filter(function (el, index, array) { 
      return array.indexOf (el) == index;
    });

    return uniqueArray;
  }
}

Then you can apply your pipe:

<div *ngFor="let item of items | filterUnique">   
    <ion-list *ngFor="let subitem of item.items" (click)="authorquotes(subitem.author);">
        <ion-item >
            {{ subitem.author }} 
        </ion-item>
    </ion-list>
</div>

Working demo: https://plnkr.co/edit/yxvoKVD3Nvgz0T3AB7w3?p=preview