Skip to content

Instantly share code, notes, and snippets.

@yacafx
Created January 3, 2018 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yacafx/2de5218a40272cc235daeb57f301f8e2 to your computer and use it in GitHub Desktop.
Save yacafx/2de5218a40272cc235daeb57f301f8e2 to your computer and use it in GitHub Desktop.
Order by text or number for angular
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