Dav*_*vid 5 javascript sorting vue.js vuetify.js
我在 vueJS 中有一个 v-data-table,其中包含一些数字列和一些字符串列。在每列中,某些值为空。我正在尝试创建一个自定义排序函数,将空值放在最后。这是我到目前为止所尝试的:
<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"
/>
Run Code Online (Sandbox Code Playgroud)
和这个功能
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;
}
Run Code Online (Sandbox Code Playgroud)
它适用于该数字列 (dp1),但不适用于字符串一 (dp2)。有什么想法如何完成这项工作吗?
您的排序算法不适用于字符串。
想象一下您的第一个字符串是null,第二个字符串是'Jelly bean'。null你试图Infinity与价值相比较,而不是价值'Jelly bean'。
false这种比较将在两种情况下进行:
let a = Infinity;
let b = 'Jelly bean';
console.log(a > b);
console.log(a < b);Run Code Online (Sandbox Code Playgroud)
最好使用另一种排序算法。
例如,我改编了这篇文章中的算法:
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以在 CodePen 上进行测试。对于字符串和数字都适用。
| 归档时间: |
|
| 查看次数: |
1541 次 |
| 最近记录: |