I am building an abstract table, each column in the table can contain either all numbers or all strings. Each column should be sortable by clicking on the column header.
Currently I am using JS native sort and passing a compareFunction:
const rows = [
{name: 'Adam', age: 27, rank: 3},
{name: 'Zeek', age: 31, rank: 1},
{name: 'Nancy', age: 45, rank: 4},
{name: 'Gramps', age: 102, rank: 2},
]
const compareFn = (x, y) => {
const sortDirValue = this.state.sortDirection === 'DESC' ? 1 : -1
if (x[this.state.sortBy] === y[this.state.sortBy]) return 0
return x[this.state.sortBy] < y[this.state.sortBy] ? sortDirValue : -sortDirValue
}
this.state = {
sortBy: 'name',
sortDirection: 'ASC'
}
rows.sort(compareFn)
console.log('---- Sorted by alphabetical name ----')
console.log(rows)
this.state = {
sortBy: 'age',
sortDirection: 'DESC'
}
rows.sort(compareFn)
console.log('---- Sorted by descending age ----')
console.log(rows)
In all the test cases I've tried so far this appears to work. However, I know JS can be finicky with sorting, like how out of the box sort()
will sort arrays of numbers alphabetically.
Can I rely on consistent correct sorting of both numbers and strings with the above approach? If not, what is an example of data that will not be sorted properly this way.