按字母顺序排列项目列表

时间:2014-01-14 21:31:53

标签: javascript list sorting alphabetical

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

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

,结果应为:

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

3 个答案:

答案 0 :(得分:1)

array.sort()正是您要找的。

Here are the docs on MDN

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

答案 1 :(得分:0)

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

阅读这些链接中的内容,您可以先按字母顺序排序,然后按数字顺序排序。

答案 2 :(得分:0)

最简单,最干净的方法是:

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