angular pipe for ranking array values

Solutions on MaxInterview for angular pipe for ranking array values by the best coders in the world

showing results for - "angular pipe for ranking array values"
Sarah
31 Sep 2019
1Pass both the property key and the array specifying the ranking to the pipe
2
3@Pipe({name: 'orderBy'}) export class OrderByPipe {
4  transform<T>(items: T[], key: keyof T, rankings?: Array<T[typeof key]>) {
5    const results = items.slice();
6
7    if (rankings) {
8      return results.sort(({[key]: leftValue}, {[key]: rightValue}) => {
9        const leftRank = rankings.indexOf(leftValue);
10        const rightRank = rankings.indexOf(rightValue);
11        return leftRank < rightRank ? 1 : leftRank === rightRank ? 0 : -1;
12      });
13    }
14    else {
15      return results.sort(({[key]: leftValue}, {[key]: rightValue}) => {
16        return String(leftValue).localeCompare(String(rightValue));
17      });
18    }
19  }
20}
21Usage:
22
23<p>Order by:</p>
24<ul>
25  <li *ngFor="let o of meetings | OrderBy : 'priority' : priority">
26    {{o.title}} {{o.priority}}
27  </li>
28</ul>
29Since we made rankings optional, we can use this for basic ordering scenarios as well.
30
31<p>Order by:</p>
32<ul>
33  <li *ngFor="let o of meetings | OrderBy : 'title'">
34    {{o.title}} {{o.priority}}
35  </li>
36</ul>