【问题标题】:How can I sort these numerical strings in ascending order? [closed]如何按升序对这些数字字符串进行排序? [关闭]
【发布时间】:2015-12-18 12:07:50
【问题描述】:

我尝试使用.sort() 对数组进行排序,但输出不是我所期望的。

arr = ["0_11_6_comment", "0_3_6_comment", "0_5_4_comment"]
arr.sort();

这是我的预期输出:

["0_3_6_comment", "0_5_4_comment", "0_11_6_comment"]

但我得到了这个:

["0_11_6_comment", "0_3_6_comment", "0_5_4_comment"]

【问题讨论】:

  • 表示您要使用第二个整数值进行排序:0_3_6_comment。 3
  • 嗯,你排序是因为第二个整数值1
  • 我不知道您实际上要做什么,因为我们仍在等待其他信息,但我想您知道接受的答案无法对这样的数组进行排序:@ 987654326@。下次,请随时reply to comments,以帮助人们提供更好的帮助。

标签: javascript arrays sorting


【解决方案1】:

数组正在排序,虽然它是按字典顺序排序,而不是数字,这可能不是您想要的。如果您想更改sort() 方法的排序方式,您需要提供您自己的“排序”含义定义。通过将比较函数作为参数传递来做到这一点。

更多详情请看这里:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

【讨论】:

    【解决方案2】:

    如果您想根据第二个整数值进行排序。使用这个:

    var arr = ["0_11_6_comment", "0_3_6_comment", "0_5_4_comment"];
    alert(arr);
    arr = arr.sort(function(a,b) {
        return parseFloat(a.split("_")[1]) - parseFloat(b.split("_")[1]) 
    });
    alert(arr);
    

    DEMO

    【讨论】:

      【解决方案3】:

      Here's a JSFiddle with the answer

      我建议阅读this

      ary.sort(function (a, b) {
        return getSecondInteger(a) > getSecondInteger(b) ? 1 : -1;
      });
      
      function getSecondInteger (str) {
        return Number(str.split('_')[1]);
      }
      

      【讨论】:

        【解决方案4】:

        试试这个

        var arr = ["0_11_6_comment", "0_3_6_comment", "0_5_4_comment", "1_2_3_comment"];
        arr.sort(function(a, b){
          a = a.match(/\d+/g);
          b = b.match(/\d+/g);
          return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
        });
        
        console.log(arr)
        // result is ["0_3_6_comment", "0_5_4_comment", "0_11_6_comment", "1_2_3"] 
        

        试试demo

        【讨论】:

        【解决方案5】:

        试试这个:

        a.sort(function (a, b) {
            // '1_2_3_comment'.split('_')
            // gives ["1", "2", "3", "comment"]
            a = a.split('_');
            b = b.split('_');
            // if a[i] - b[i] = 0 then check next
            return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
        });
        

        阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-03
          • 1970-01-01
          • 2013-10-28
          • 1970-01-01
          • 2021-05-17
          • 2018-06-06
          • 2013-06-20
          相关资源
          最近更新 更多