【问题标题】:custom sorting v-data-table with null values last最后使用空值自定义排序 v-data-table
【发布时间】:2022-01-02 17:46:33
【问题描述】:

我在 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)。 任何想法如何完成这项工作?

【问题讨论】:

    标签: javascript vue.js sorting vuetify.js


    【解决方案1】:

    您的排序算法不适用于字符串。

    假设您的第一个字符串是null,第二个字符串是'Jelly bean'。 您尝试将 Infinity'Jelly bean' 比较,而不是 null 值。

    这两种情况下的比较结果都是false

    let a = Infinity;
    let b = 'Jelly bean';
    console.log(a > b);
    console.log(a < b);

    最好使用其他排序算法。

    例如,我改编了一个算法from this post

    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;
    }
    

    你可以测试这个at CodePen。适用于字符串和数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      相关资源
      最近更新 更多