【问题标题】:How to sort an alphanumeric array just based on number in javascript?如何仅根据javascript中的数字对字母数字数组进行排序?
【发布时间】:2021-11-09 14:16:13
【问题描述】:

考虑以下数组:

['state1035', 'dm5', 'state123', 'county247', 'county2']

根据数字输出对该数组进行排序应该是:

['county2' ,'dm5', 'state123', 'county247', 'state1035']

【问题讨论】:

    标签: javascript sorting arraylist


    【解决方案1】:

    假设字符串将包含数字,最后您可以使用 match 提取数字并对其进行排序:

    let arr = ['state1035', 'dm5', 'state123', 'county247', 'county2'];
    console.log(arr.sort((a,b) => a.match(/\d+$/).pop() - b.match(/\d+$/).pop()));

    比较函数中使用的匹配方法将返回给定字符串中匹配的子字符串数组。正则表达式\d+ 将匹配末尾的数字,我们将根据这些数字进行排序。

    【讨论】:

      【解决方案2】:

      仅针对字符串中的数字使用regular expressionmatch,然后根据这些数字使用sort 字符串。

      const data = ['state1035', 'dm5', 'bob0Bob', 'state123', 'county247', 'county2'];
      
      const regex = /\d+/;
      
      const result = data.sort((a, b) => {
        return a.match(regex) - b.match(regex);
      });
      
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-05
        • 2018-11-02
        • 2011-02-06
        • 2019-03-16
        相关资源
        最近更新 更多