I am using Backgrid. I found that one of my columns has 'undefined' value. Backgrid sorting doesn't work correctly when there is undefined in the column. I looked into the source code.
onClick: function (e) { e.preventDefault();
var columnName = this.column.get("name");
if (this.column.get("sortable")) {
if (this.direction() === "ascending") {
this.sort(columnName, "descending", function (left, right) {
var leftVal = left.get(columnName);
var rightVal = right.get(columnName);
if (leftVal === rightVal) {
return 0;
}
else if (leftVal > rightVal) { return -1; }
return 1;
});
}
else if (this.direction() === "descending") {
this.sort(columnName, null);
}
else {
this.sort(columnName, "ascending", function (left, right) {
var leftVal = left.get(columnName);
var rightVal = right.get(columnName);
if (leftVal === rightVal) {
return 0;
}
else if (leftVal < rightVal) { return -1; }
return 1;
});
}
}
},
I changed the code to the following and sorting works correctly (assume undefined is less than any value):
onClick: function (e) { e.preventDefault();
var columnName = this.column.get("name");
if (this.column.get("sortable")) {
if (this.direction() === "ascending") {
this.sort(columnName, "descending", function (left, right) {
var leftVal = left.get(columnName);
var rightVal = right.get(columnName);
if (leftVal === undefined && rightVal != undefined) {
return 1;
}
if (leftVal != undefined && rightVal === undefined) {
return -1;
}
if (leftVal === rightVal) {
return 0;
}
else if (leftVal > rightVal) { return -1; }
return 1;
});
}
else if (this.direction() === "descending") {
this.sort(columnName, null);
}
else {
this.sort(columnName, "ascending", function (left, right) {
var leftVal = left.get(columnName);
var rightVal = right.get(columnName);
if (leftVal === undefined && rightVal != undefined) {
return -1;
}
if (leftVal != undefined && rightVal === undefined) {
return 1;
}
if (leftVal === rightVal) {
return 0;
}
else if (leftVal < rightVal) { return -1; }
return 1;
});
}
}
},
Is there any other way to deal with undefined value when sorting? Thanks!