Skip to content

Commit

Permalink
fix(sortable-table): support mixed content and floating values
Browse files Browse the repository at this point in the history
The Sortable table component now supports sorting decimal (float) values natively, and sorting mixed content (text and numeric values in the same column). It's also better at sorting text containing non-English-alphabet characters.

Fixes #559 

---------

Co-authored-by: Lee Jacobson <[email protected]>
  • Loading branch information
smcveigh941 and leejacobson-moj authored Feb 19, 2024
1 parent db95dbf commit e4f9e69
Showing 1 changed file with 12 additions and 27 deletions.
39 changes: 12 additions & 27 deletions src/moj/components/sortable-table/sortable-table.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,37 +103,22 @@ MOJFrontend.SortableTable.prototype.getTableRowsArray = function() {
};

MOJFrontend.SortableTable.prototype.sort = function(rows, columnNumber, sortDirection) {
var newRows = rows.sort($.proxy(function(rowA, rowB) {
var newRows = rows.sort((function(rowA, rowB) {
var tdA = $(rowA).find('td,th').eq(columnNumber);
var tdB = $(rowB).find('td,th').eq(columnNumber);
var valueA = this.getCellValue(tdA);
var valueB = this.getCellValue(tdB);
if(sortDirection === 'ascending') {
if(valueA < valueB) {
return -1;
}
if(valueA > valueB) {
return 1;
}
return 0;
} else {
if(valueB < valueA) {
return -1;
}
if(valueB > valueA) {
return 1;
}
return 0;
}
}, this));

var valueA = sortDirection === 'ascending' ? this.getCellValue(tdA) : this.getCellValue(tdB);
var valueB = sortDirection === 'ascending' ? this.getCellValue(tdB) : this.getCellValue(tdA);

if (typeof valueA === 'string' || typeof valueB === 'string') return valueA.toString().localeCompare(valueB.toString());
return valueA-valueB;
}.bind(this)));
return newRows;
};

MOJFrontend.SortableTable.prototype.getCellValue = function(cell) {
var val = cell.attr('data-sort-value');
val = val || cell.html();
if($.isNumeric(val)) {
val = parseInt(val, 10);
}
return val;
var val = cell.attr('data-sort-value') || cell.html();

var floatVal = parseFloat(val)
return isNaN(floatVal) ? val : floatVal
};

0 comments on commit e4f9e69

Please sign in to comment.