angular pipe for ranking array values code example

Example: angular pipe for ranking array values

Pass both the property key and the array specifying the ranking to the pipe

@Pipe({name: 'orderBy'}) export class OrderByPipe {
  transform<T>(items: T[], key: keyof T, rankings?: Array<T[typeof key]>) {
    const results = items.slice();

    if (rankings) {
      return results.sort(({[key]: leftValue}, {[key]: rightValue}) => {
        const leftRank = rankings.indexOf(leftValue);
        const rightRank = rankings.indexOf(rightValue);
        return leftRank < rightRank ? 1 : leftRank === rightRank ? 0 : -1;
      });
    }
    else {
      return results.sort(({[key]: leftValue}, {[key]: rightValue}) => {
        return String(leftValue).localeCompare(String(rightValue));
      });
    }
  }
}
Usage:

<p>Order by:</p>
<ul>
  <li *ngFor="let o of meetings | OrderBy : 'priority' : priority">
    {{o.title}} {{o.priority}}
  </li>
</ul>
Since we made rankings optional, we can use this for basic ordering scenarios as well.

<p>Order by:</p>
<ul>
  <li *ngFor="let o of meetings | OrderBy : 'title'">
    {{o.title}} {{o.priority}}
  </li>
</ul>