Reputation: 12015
I have pipe that sorts by array by date property.
Problem is that not each elements has property date in args.key
. So there rows should be in bottom of list.
import {
Pipe,
PipeTransform
} from "@angular/core";
@Pipe({
name: 'sort'
})
export class ArraySortPipe implements PipeTransform {
transform(records: Array < any > , args ? : {
key: string,
direction: boolean,
type: "int" | "string" | "date"
}): any {
return records.sort(function (a: any, b: any) {
if (args.type === 'date' && args.direction) {
return new Date(a[args.key]).getTime() - new Date(b[args.key]).getTime();
}
});
};
}
How to move properties without date to the bottom of list?
Upvotes: 0
Views: 729
Reputation: 14679
You could ad another return values for the sorting function: if a
doesn't have date, return -1. If b
doesn't have date, return 1.
Like:
transform(records: Array < any > , args ? : {
key: string,
direction: boolean,
type: "int" | "string" | "date"
}): any {
return records.sort(function (a: any, b: any) {
if (args.type === 'date' && args.direction) {
if(!a[args.key]) {
return -1;
}
if(!b[args.key]) {
return 1;
}
return new Date(a[args.key]).getTime() - new Date(b[args.key]).getTime();
}
});
};
(Direction not implemented).
Upvotes: 1