5

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.

12
  • you mean unique records? Commented Apr 20, 2017 at 7:08
  • Create a list of unique items in your controller, and loop over that. Commented Apr 20, 2017 at 7:09
  • *ngFor can't help you here. You can create a pipe that filters duplicates, or you can use a list in *ngFor that already has the duplicates filtered. Commented Apr 20, 2017 at 7:10
  • stackoverflow.com/questions/11246758/… Commented Apr 20, 2017 at 7:10
  • 1
    That doesn't sound like a good argument. Angular executes it only when the value changes (different array instance). If you make the pipe impure, you can still cache the result and returned cached result as long as the parameters or input values haven't changed. That doesn't seem worse than other approaches. Commented Apr 20, 2017 at 7:22

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

3 Comments

Instead of using filter and indexOf, you can use ES6 Set stackoverflow.com/a/33121880/6806381
@ChristopherMoore thank you :) It's a good approach. Later I can update my post with your ES6 solution.
Hi how to use this pipe in ion-virtual-scroll?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.