【问题标题】:Sorting table column by id and field not working按 id 和字段对表列进行排序不起作用
【发布时间】:2021-01-30 06:14:41
【问题描述】:

我使用以下方法对可重复使用的 Material 数据表中的数据(数组)进行排序:

sortData(sortParameters: Sort) {
    const keyName = sortParameters.active;
    if (sortParameters.direction === 'asc') {
      this.tableData = this.tableData.sort((a, b) => a[keyName].localeCompare(b[keyName]));
    }
    else if (sortParameters.direction === 'desc') {
      this.tableData = this.tableData.sort((a, b) => b[keyName].localeCompare(a[keyName]));
    }
    else {
      this.getStudents();
    }
}

但是,虽然它适用于 name 字段,但它不适用于 id 字段。关于此方法的另一个问题是我想忽略 name 的空格并希望将 trim() 方法用于排序值。它正在工作,但我认为我必须找到另一种适用于 id 列的解决方案。有什么解决办法吗?

【问题讨论】:

  • id中值的类型是什么?它也是字符串还是其他什么?
  • @ChristianFritz 它们是整数,而不是字符串。 1,2,3 等值(顺序 id 值)。
  • 关于排序 int 和 string 值的任何想法?
  • 那么问题来了:JS 中的数字没有 localeCompare 函数。您需要实现一个排序函数,该函数将根据typeof a[keyName] 区分大小写,或者更好的是,为每个键设置单独的排序函数。

标签: javascript angularjs angular typescript ecmascript-6


【解决方案1】:

最简单的方法是使用 d3 的升序()和降序()。

import {ascending, descending} from 'd3-array';

sortData(sortParameters: Sort) {
    const keyName = sortParameters.active;

    if (sortParameters.direction === 'asc') {
      this.tableData = this.tableData.sort((a, b) => 
    a_prop = a[keyName];
    b_prop = b[keyName];
    try {
      a_prop = a_prop.trim();
      b_prop = b_prop.trim();
    } catch (error) {
      //do nothing, must not have been a string
    }
ascending(a_prop, b_prop);
    }
    else if (sortParameters.direction === 'desc') {
descending(a_prop,b_prop);

      }
    else {
      this.getStudents();
    }
}

作为导入 D3.js 的替代方法,将函数的代码直接粘贴到您的代码中,因为它们很短。取自 https://github.com/d3/d3-array/blob/master/src/ascending.js

ascending (a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
descending (a, b) {
    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

【讨论】:

  • 非常感谢,这是非常好的解决方案。我做了一些小修改并发布它们。问候。
【解决方案2】:

localeCompare 是字符串的函数,但如果您的其他列(如id)不是字符串,则不能使用它对它们进行排序。然后,您需要为每种类型提供单独的排序功能。这是执行此操作的一种方法:

const defaultSort = (a, b) => a < b;
const sortFunctions = {
  id: (a, b) => a < b,
  name: (a, b) => a.localeCompare(b),
  // ....
};

function sortData(sortParameters: Sort) {
  const keyName = sortParameters.active;
  const sortFunction = sortFunctions[keyName] || defaultSort;
  if (sortParameters.direction === 'asc') {
    this.tableData = this.tableData.sort((a, b) => sortFunction(a, b));
  }
  else if (sortParameters.direction === 'desc') {
    this.tableData = this.tableData.sort((a, b) => sortFunction(b, a));
  } else {
    this.getStudents();
  }
}

【讨论】:

  • 你可以为 TypeScript 编辑它吗?我无法修复某些部分。提前致谢。
  • 其实我还没学过打字稿,但我一直认为javascript也是有效的打字稿,这意味着类型描述符是可选的。不是这样吗?我的代码出现了什么错误?
  • 可能与 sortFunctions 的参数有关的 linting 问题(如果我不得不冒险猜测的话)。除非配置了非常严格的编译器选项,否则它不应阻止运行。
  • 是的,你是对的。我通过添加一些修改来使用@Katherine 的解决方案。但你的回答也很有帮助,我投了赞成票;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
相关资源
最近更新 更多