Reputation: 341
Say I have a list of items, which are sorted using a given comparator. I would expect that after sorting into ascending order comparator(element[1], element[1+n]) should return -1 for all values of n> 1, because according to that comparator, element[1]
I am performing a custom sort and finding that after sorting there are instances where comparator(element[1], element[1+n]) returns 1. When I look at the instance I see that the comparator giving the correct output, i.e. element[1]>element[1+n]. I don't understand how this could be the case after performing a sort with that comparator.
If anyone has any idea of sort subtleties that I might have missed, I'd really appreciate their thoughts. Also, if I can provide more information that might shed light please let me know.
edit I thought this might be a more general question, but in response to mplungjan have added the custom sorter below. The sort is for a hierarchical dataset in the form of a flat list of objects. Each object has an id which might be as follows: 0 for root 1. 0-0 for its first child. 0-1 for its second child. etc.
Each object in the list had a field 'parent' which has the id of its parent. Essentially data.sort isn't doing what I think it should be.
function CurrencyTreeSorter(a, b) {
a_id = a.id.split("-");
b_id = b.id.split("-");
if(a_id.length != b_id.length || a_id.slice(0, a_id.length-1).toString() != b_id.slice(0, b_id.length-1).toString()){
var i = 0;
while (i < a_id.length && i < b_id.length && a_id[i] == b_id[i]) {
i++;
}
if (i == a_id.length || i == b_id.length){
return a_id.length > b_id.length ? 1 : -1;
}
else{
while (a.level > i) {
a = getParent(dataMap, a);
}
while (b.level > i) {
b = getParent(dataMap, b);
}
}
}
var x, y;
if (a[sortcol] == "-") {
x = -1;
}
else {
x = parseFloat(a[sortcol].replace(/[,\$£€]/g, ""));
}
if (b[sortcol] == "-") {
y = -1;
}
else {
y = parseFloat(b[sortcol].replace(/[,\$£€]/g, ""));
}
return sortdir * (x == y ? 0 : (x > y ? 1 : -1));
}
Upvotes: 0
Views: 865