0

I am working on Angular project where I want to short players by playerCreditPoint in desending order from below json

0: {playerName: "Imran Tahir",  country: "Dolphins", playerCreditPoint: "1.50"}
1: {playerName: "xyx",  country: "Dolphins", playerCreditPoint: "6.50"}
2: {playerName: "abc",  country: "Dolphins", playerCreditPoint: "4.50"}
3: {playerName: "def",  country: "Dolphins", playerCreditPoint: "11.50"}
4: {playerName: "mno",  country: "Dolphins", playerCreditPoint: "10.50"}
5: {playerName: "pqr",  country: "Dolphins", playerCreditPoint: "9.50"}

for that I am using pipes

 <div class="all_players" *ngFor="let player of players | orderBy :player; let pIndex = index">

But it is not working as giving error The pipe 'orderBy' could not be foundAngular

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
Anurag Ranjan
  • 169
  • 1
  • 2
  • 9

2 Answers2

1

Angular does not have an OrderBy or filter pipe by default: https://angular.io/guide/pipes#no-filter-pipe But the next snippet might be of some help. Please add your own type checks if item contains strings or non arr datatypes.

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

@Pipe({
    name: 'orderBy'
})
export class OrderBy implements PipeTransform {
    transform(array, orderBy) {
        // descending
        return Array.from(array).sort((item1: any, item2: any) =>
            this.comparator(item2[orderBy], item1[orderBy])
        );
    }

    comparator(a: any, b: any): number {
        if (parseFloat(a) < parseFloat(b)) {
            return -1;
        }
        if (parseFloat(a) > parseFloat(b)) {
            return 1;
        }

        return 0;
    }
}

Without the angular sauce, what you are looking for is essentially

const data = [
  { playerName: "Imran Tahir", country: "Dolphins", playerCreditPoint: 1.5 },
  { playerName: "xyx", country: "Dolphins", playerCreditPoint: 6.5 },
  { playerName: "abc", country: "Dolphins", playerCreditPoint: 4.5 },
  { playerName: "def", country: "Dolphins", playerCreditPoint: 11.5 },
  { playerName: "mno", country: "Dolphins", playerCreditPoint: 10.5 },
  { playerName: "pqr", country: "Dolphins", playerCreditPoint: 9.5 }
];

function orderBy(arr) {
  return arr.sort((item1: any, item2: any) => {
    return comparator(item2, item1);
  });
}

function comparator(a: any, b: any) {
  return a.playerCreditPoint - b.playerCreditPoint;
}

console.log(orderBy(data));

Oz Lodriguez
  • 965
  • 5
  • 16
0

Angular does not have orderBy pipe.

Alternatively, you can use ngx-order-pipe or You can create your own pipe for sorting.

Link: https://www.npmjs.com/package/ngx-order-pipe

OR

Go to this link for creating your own pipe.

Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52