首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义排序v-数据表,最后为空值。

自定义排序v-数据表,最后为空值。
EN

Stack Overflow用户
提问于 2022-01-02 17:46:33
回答 1查看 820关注 0票数 5

我在vueJS中有一个v数据表,它包含一些数字列和一些字符串列。在每一列中,有些值为空。我正在尝试创建一个自定义排序函数,该函数将空值放置在最后。这就是我迄今为止尝试过的:

代码语言:javascript
复制
<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"
      />

而这个功能

代码语言:javascript
复制
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)。有什么办法能得到这份工作吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-03 06:13:19

您的排序算法不能正确地处理字符串。

假设第一个字符串是null,第二个字符串是'Jelly bean'。与null值不同,您正在尝试将Infinity'Jelly bean'组合起来。

在这两种情况下,这种比较都是false

代码语言:javascript
复制
let a = Infinity;
let b = 'Jelly bean';
console.log(a > b);
console.log(a < b);

最好使用另一种排序算法。

例如,我采用了一个算法从这个岗位上

代码语言:javascript
复制
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。对字符串和数字都很好。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70558324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档