【问题标题】:Arrange list of items in alphabetical order按字母顺序排列项目列表
【发布时间】:2014-01-14 21:31:52
【问题描述】:

我们如何在javascript中按字母顺序排列以下项目列表?

Item 1, Item 12, Item 3, Item 4, Item 5

结果应该是:

Item 1, Item 3, Item 4, Item 5, Item 12

【问题讨论】:

  • 你想要按字母排序,或者Item 3Item 12 之前?
  • 啊哈,好问题@RaphaëlAlthaus。
  • 我感觉Item 12 是一个错字,因为其他所有内容都增加了 1。
  • @knrz 但是为什么要对已经排序的东西进行排序呢?
  • 我认为他只是抽象了他的字符串。无论如何,让我们等到OP澄清。

标签: javascript list sorting alphabetical


【解决方案1】:

array.sort() 就是你要找的东西。

Here are the docs on MDN.

[Item1, Item2, Item3, Item4, Item5].sort()

【讨论】:

    【解决方案2】:

    您正在寻找的是自然排序,这可以帮助您:

    阅读这些链接中的内容,您将能够先按字母顺序排列项目,然后再按数字顺序排列。

    【讨论】:

      【解决方案3】:

      最简单干净的方法是这样的:

      var your_array = [item 1, item 2, item 3, ...item i];
      var sorted_array = your_array.sort(); //this sorts alphabetically but not numerically
      
      var sortedNumerically = your_array.sort(function(a,b){ return a-b;}) //this sorts numerically in ascending order
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多