【发布时间】:2018-01-27 08:18:11
【问题描述】:
我正在构建一个抽象表,表中的每一列可以包含所有数字或所有字符串。每一列都应该可以通过单击列标题进行排序。
目前我正在使用 JS native sort 并传递一个 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)
到目前为止,在我尝试过的所有测试用例中,这似乎都有效。但是,我知道 JS 对排序可能很挑剔,比如开箱即用的sort() 将如何sort arrays of numbers alphabetically。
我可以依靠上述方法对数字和字符串进行一致的正确排序吗?如果不能,有哪些数据不会以这种方式正确排序的示例。
【问题讨论】:
-
@CumuloNimbus 不,您的比较函数认为相等的字符串是不同的。
-
@melpomene 现在它应该处理相等的情况,感谢您的彻底
标签: javascript