我在 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"
/>
和這個功能
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)。任何想法如何獲得這項作業?
uj5u.com熱心網友回復:
您的排序演算法對字串無法正常作業。
想象一下,您的第一個字串是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://www.uj5u.com/qukuanlian/402898.html
標籤:
