1

How do we arrange the following list of item in alphabetical order in javascript?

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

and the result should be:

Item 1, Item 3, Item 4, Item 5, Item 12
  • 5
    you want alphabetical sort, or `Item 3` before `Item 12` ? – Raphaël Althaus Jan 14 '14 at 21:33
  • Aha good question @RaphaëlAlthaus. – Pavan Jan 14 '14 at 21:35
  • I have a feeling that `Item 12` was a typo, since everything else is incremented by 1. – knrz Jan 14 '14 at 21:35
  • @knrz but why sort something which is already sorted, then ? – Raphaël Althaus Jan 14 '14 at 21:36
  • I think he just abstracted his strings. Anyway, let's wait until the OP clarifies. – knrz Jan 14 '14 at 21:37
  • I believe that OP, is not lazy, and that 12 is not a typo, bets?. Also if this is not a typo, then question is a duplicate. – rscnt Jan 14 '14 at 21:39
  • In case you want natural sort, see http://stackoverflow.com/q/15478954/989121 – georg Jan 14 '14 at 21:44
  • also: http://stackoverflow.com/questions/14599321/javascript-natural-sort – rscnt Jan 14 '14 at 21:47
  • Thanks for your replies and sorry for the confusion. But that's not a typo. I want the result to be [Item 1, Item 3, Item 4, Item 5, Item 12]. Is this possible in javascript? BTW, others are suggesting me to split each item and only get the numbers to sort it. But I don't want to do it that way because what if those items are inserted dynamically and we don't know what are the items to be sorted. Please let me know if this still confuses you. Thanks! – user3195839 Jan 15 '14 at 12:46
  • Men, search for natural sorting that's everything you need. – rscnt Jan 28 '14 at 20:16

3 Answers3

1

array.sort() is what you're looking for.

Here are the docs on MDN.

[Item1, Item2, Item3, Item4, Item5].sort()
knrz
  • 1,801
  • 1
  • 12
  • 15
0

What you're looking for is natural sorting, this could help you:

Reading the content in these links you'll be able to order items first alphabetical, then numerical.

rscnt
  • 985
  • 9
  • 13
0

The most easy and clean way is this:

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
Bee
  • 88
  • 3