我在vueJS中有一个v数据表,它包含一些数字列和一些字符串列。在每一列中,有些值为空。我正在尝试创建一个自定义排序函数,该函数将空值放置在最后。这就是我迄今为止尝试过的:
<v-data-table
:headers="[
{ text: 'Name', value: 'name' },
{ text: 'Date of Birth', value: 'dateofbirth_fmt' },
{ text: 'Team', value: 'team_name' },
{
text: 'dp1 (string)',
value: 'dp1',
},
{
text: 'dp2 (Numeric),
value: 'dp2',
}
]"
:items="filteredPlayersData"
item-key="_id"
class="elevation-1"
:custom-sort="customSort"
/>而这个功能
customSort(items, index, isDesc) {
items.sort((a, b) => {
if (!isDesc[0]) {
return (a[index] != null ? a[index] : Infinity) >
(b[index] != null ? b[index] : Infinity)
? 1
: -1;
} else {
return (b[index] != null ? b[index] : -Infinity) >
(a[index] != null ? a[index] : -Infinity)
? 1
: -1;
}
});
return items;
}它适用于此数值列(dp1),但不适用于字符串列(dp2)。有什么办法能得到这份工作吗?
发布于 2022-01-03 06:13:19
您的排序算法不能正确地处理字符串。
假设第一个字符串是null,第二个字符串是'Jelly bean'。与null值不同,您正在尝试将Infinity与'Jelly bean'组合起来。
在这两种情况下,这种比较都是false:
let a = Infinity;
let b = 'Jelly bean';
console.log(a > b);
console.log(a < b);
最好使用另一种排序算法。
例如,我采用了一个算法从这个岗位上
customSort(items, index, isDesc) {
items.sort((a, b) => {
if (a[index] === b[index]) { // equal items sort equally
return 0;
} else if (a[index] === null) { // nulls sort after anything else
return 1;
} else if (b[index] === null) {
return -1;
} else if (!isDesc[0]) { // otherwise, if we're ascending, lowest sorts first
return a[index] < b[index] ? -1 : 1;
} else { // if descending, highest sorts first
return a[index] < b[index] ? 1 : -1;
}
});
return items;
}您可以测试这个在CodePen。对字符串和数字都很好。
https://stackoverflow.com/questions/70558324
复制相似问题