【问题标题】:Sorting numbers cast as strings in react在反应中将数字排序为字符串
【发布时间】:2021-03-18 18:40:36
【问题描述】:

背景

我的数据包含像“1,000”和“123,000”这样的字符串,我想在材料表中对它们进行排序。 我希望它们从数字角度而不是字符串角度按值排序。

问题

当我仍然希望单元格包含字符串格式允许的逗号时,如何按数字值而不是字符串字母顺序对单元格进行排序。

到目前为止的代码

我正在尝试在这里进行工资排序:

function CustomFilteringAlgorithm() {
  return (
    <MaterialTable
      title="Custom Filtering Algorithm Preview"
      columns={[
        {
          title: 'Name', 
          field: 'name',
          customSort: (a, b) => a.name.length - b.name.length
        },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        { title: 'Salary', field: 'salary', type: 'numeric',
          customSort: (a, b) => parseInt(a.salary) - parseInt(b.salary),
        },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}
      data={[
        { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63, salary: '123,000' },
        { name: 'Joe', surname: 'Baran', birthYear: 1947, birthCity: 63, salary: '1,000' },
        { name: 'John', surname: 'Smith', birthYear: 1988, birthCity: 63, salary: '2,000' },
        { name: 'Jaun', surname: 'Smittle', birthYear: 1988, birthCity: 63, salary: '4,000' },
        { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017, birthCity: 34, salary: '45,000' },
        { name: 'Vishal', surname: 'Miller', birthYear: 2000, birthCity: 34, salary: '15,000,000' },
      ]}
      options={{
        sorting: true
      }}
    />
  )
}

注意

可以使用this page 上的自定义排序部分来测试代码:

【问题讨论】:

    标签: reactjs material-table


    【解决方案1】:

    parseInt() 不适用于包含逗号的字符串,您必须在排序时手动删除它们:

    customSort: (a, b) => parseInt(a.salary.replace(/,/g, '')) - parseInt(b.salary.replace(/,/g, ''))
    

    【讨论】:

    • @Romulus 考虑类似于下面其他答案的建议的内容,您将数据存储为状态中的真实数字,并且仅在您想将它们显示给用户时将它们转换/格式化为字符串。 一般最好以原始形式存储数字,以便您可以轻松比较和操作它们,而不是作为字符串。
    【解决方案2】:

    试试这个, 首先用于排序转换为数字

    const salary = Number(('123,000').replace(',', ''));
    

    那么,

    const salaryString = salary.toLocaleString('en');
    

    【讨论】:

      猜你喜欢
      • 2012-01-20
      • 2021-11-22
      • 2010-11-18
      • 2015-09-28
      • 1970-01-01
      • 2019-01-24
      • 2016-02-14
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多