javascript - Vue用空单元格排序导致不同的结果
问题描述
我创建了一个根据 asc 和 desc 顺序排序的表。当单元格不为空时它工作正常,但是当它为空时,每次在升序和降序之间切换时结果都会改变。
这是我的排序代码:
methods:{
sort:function(filter) {
//if filter == current sort, reverse
if(filter === this.currentSort) {
this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
}
this.currentSort = filter;
},
和计算:
computed:{
sortedPeople:function() { //sort by current sorting direction
return this.people.sort((a,b) => {
let modifier = 1;
if(this.currentSortDir === 'desc') modifier = -1;
if(a[this.currentSort] == null || b[this.currentSort] == null){
return -1;
}
if(a[this.currentSort] <= b[this.currentSort]){
return -1 * modifier;
}
if(a[this.currentSort] > b[this.currentSort]) {
return 1 * modifier;
}
return 0;
}).filter((row, index) => { //limit view and not repeat due to pagination
let start = (this.currentPage-1)*this.pageSize;
let end = this.currentPage*this.pageSize;
if(index >= start && index < end) return true;
});
}
}
我试图将空单元格排序到最后,但我的方法不能 100% 工作,我真的不明白为什么它们会在开关之间改变。
编辑:我调整了我的代码,现在它们都被排序在一起,但是它们在开头的“a”之前排序,而不是结尾,我不确定如何将它排序到最后。
sortedPeople:function() { //sort by current sorting direction
return this.people.sort((a,b) => {
let modifier = 1;
if(this.currentSortDir === 'desc') modifier = -1;
if(a[this.currentSort] == null){ //CHANGED CODE
a[this.currentSort] = "";
} else if (b[this.currentSort] == null){
b[this.currentSort] = "";
}
if(a[this.currentSort] < b[this.currentSort]){
return -1 * modifier;
}
if(a[this.currentSort] > b[this.currentSort]) {
return 1 * modifier;
}
return 0;
}).filter((row, index) => { //limit view and not repeat due to pagination
let start = (this.currentPage-1)*this.pageSize;
let end = this.currentPage*this.pageSize;
if(index >= start && index < end) return true;
});
}
解决方案
您需要在不考虑排序方向的情况下显式检查空(或null
)字符串;类似于以下内容
.sort((a,b) => {
const aValue = a[this.currentSort];
const bValue = b[this.currentSort];
if (aValue === bValue) return 0;
if (!aValue) return 1;
if (!bValue) return -1;
let direction = (aValue < bValue) ? -1 : 1;
if (this.currentSortDir === 'desc') direction *= -1;
return direction;
})
推荐阅读
- yii2 - Yii2 - 关闭模态时保持值输入
- c# - 无法运行 asp.net 核心 docker 映像 - 找不到框架“Microsoft.AspNetCore.App”,版本“2.1.1”
- arrays - 如何访问已映射到表行的数组中的特定项目?- 反应
- reactjs - React-Bootstrap 1.0.0-beta.6 偏移和 Form Col 不起作用
- ios - 在多个collectionviewcells中添加tableview
- html - 如何修复桌面和移动设备之间不一致的占位符文本垂直对齐?
- generator - Redux Saga 如何解析数据
- mocking - C++ 模拟类 - 如何解决这个多重继承问题?
- sql - 将日期字段值插入 varcharfield 以及附加的硬编码文本
- python - 使用方差膨胀因子查找属性之间的多重共线性