【问题标题】:How to correctly sort a string array in javascript [duplicate]如何在javascript中正确排序字符串数组[重复]
【发布时间】:2020-07-14 20:41:22
【问题描述】:

我有一个如下所示的数组

const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png']

我想按数字顺序对其进行排序,但仅调用 sort 是一个问题,因为排序后它会如下所示:

['1.jpeg', '10.png', '12.gif', '2.jpeg', '30.png', '4.png']

如何以“正确”的方式对其进行排序,使其看起来像这样

[ '1.jpeg', '2.jpeg', '4.png', '10.png', '12.gif', '30.png']

【问题讨论】:

    标签: javascript arrays node.js typescript sorting


    【解决方案1】:

    我们可以使用以下代码:

    const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'];
    function fileToNumber(file) {
        // we get everything before the period and convert it to a number
        return parseInt(file.split(".")[0], 10);
    }
    // we sort with a custom comparator based on our fileToNumber function
    files.sort((a, b) => fileToNumber(a) - fileToNumber(b));
    

    【讨论】:

      【解决方案2】:

      function numberPart (str){
       return parseInt(str.split('.')[0])
      }
      
      const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'];
      
      files.sort( (a,b) => numberPart(a) - numberPart(b))
      
      console.log(files)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-23
        • 1970-01-01
        • 1970-01-01
        • 2012-10-30
        • 2021-10-18
        • 2019-12-13
        • 2020-06-27
        • 1970-01-01
        相关资源
        最近更新 更多