Created
January 3, 2018 00:30
-
-
Save yacafx/2de5218a40272cc235daeb57f301f8e2 to your computer and use it in GitHub Desktop.
Order by text or number for angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
@Pipe({ name: 'orderBy' }) | |
export class OrderBy implements PipeTransform { | |
transform(array, orderBy, asc = true) { | |
if (!orderBy || orderBy.trim() == "") { | |
return array; | |
} | |
// ascending | |
if (asc) { | |
return Array.from(array).sort((item1: any, item2: any) => { | |
return this.orderByComparator(item1[orderBy], item2[orderBy]); | |
}); | |
} | |
else { | |
// not asc | |
return Array.from(array).sort((item1: any, item2: any) => { | |
return this.orderByComparator(item2[orderBy], item1[orderBy]); | |
}); | |
} | |
} | |
orderByComparator(a: any, b: any): number { | |
if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) { | |
// Isn't a number so lowercase the string to properly compare | |
if (a.toLowerCase() < b.toLowerCase()) return -1; | |
if (a.toLowerCase() > b.toLowerCase()) return 1; | |
} | |
else { | |
// Parse strings as numbers to compare properly | |
if (parseFloat(a) < parseFloat(b)) return -1; | |
if (parseFloat(a) > parseFloat(b)) return 1; | |
} | |
return 0; // equal each other | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment