Reputation: 128
I have a requirement where I need to sort each column of table every time it is clicked in ascending order. The logic applied is a general logic for sorting in Javascript. It works fine in all the scenarios except when the data comes up with different digits the column.
The code is
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
return records.sort(function(a, b){
if(a[args.property] === null){
return 1 * args.direction;
}
else if(b[args.property] === null){
return -1 * args.direction;
}
else if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
};
}
the above code fails when I get data like 844401, 76574893632,717613, 6304420005555
It sorts the values in the order listed above although it should sort 76574893632 before 844401
Upvotes: 0
Views: 1302
Reputation: 2784
From the MDN docs:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.
Given the fact that on provided code here you take as parameter an Array of type any
, I could not tell what you supply to the pipe, that is left for you to figure out.
But, I'll explain you what possibilities you have:
you supply an Array of string in the form of ["844401", "76574893632", "717613", "6304420005555"]
and you apply .sort()
on it, the result is going to be 6304420005555,717613,76574893632,844401
you supply an Array of numbers in form of [844401, 76574893632, 717613, 6304420005555]
and you apply .sort()
on it, it will treat them as Unicode
values, thus resulting in a sort applied to strings and the result is going to be the same as before: 6304420005555,717613,76574893632,844401
the third one, which I assume is the one you are looking for, is to supply an Array of numbers in form of [844401, 76574893632, 717613, 6304420005555]
, then you have to apply the sort method with a supplied compareFunction in order to be treated like numbers: .sort( (a,b) => { return a-b } )
. Then you have the result: 717613,844401,76574893632,6304420005555
I have made an implementation for you on plunkr here.
Hope it's clearer now. If you have further questions, don't hesitate.
Upvotes: 1
Reputation: 36
Check to make sure that your number comparisons are being done with the values properly parsed as integers rather than strings. Comparing two numbers in the form of strings will not necessarily produce what you would expect.
Upvotes: 1