0

I need to sort an array that looks like this:

var array = new Array();<br />
array[0]="201206031245 firstitem";<br />
array[1]="201206020800 seconditem";<br />
array[2]="201206040604 itemthree";<br />
array[3]="201206031345 lastitem";<br />

How would I sort this numerically and descending?

Thanks in advance!

2
  • 3
    BTW, when you get so many answers in couple minutes, it usually says, you didn't put a little effort solving it yourself.
    – gdoron
    Commented Jun 4, 2012 at 23:50
  • Apologies for the simple question--I did put effort into this, and am relatively novice with arrays. Sounds stupid for a JavaScript developer but it's true.
    – zdebruine
    Commented Jun 5, 2012 at 2:55

4 Answers 4

3

Just use array.sort(). It will sort alphabetical, but as long as your numbers have the same number of digits that's perfectly OK.

2

Although .sort() will by default do an alphanumeric sort, for your data it will work numerically because your array elements all start with numbers that follow a strict date/time format with the same number of digits. .sort() will sort ascending though. You could provide your own comparison function to sort descending, or you could just reverse the results:

array.sort().reverse()

For more information about how .sort() works, e.g., to provide your own comparison function, have a look at the documentation.

1
  • Thanks very much for your answer! Looking in retrospect I realize I didn't need to be so intent on the numerical sort function. This works well! Apologies for the simple question, but I appreciate the answer--it's the solution to a lot of work!
    – zdebruine
    Commented Jun 5, 2012 at 2:53
1

All you need is to call sort on your Array:

array.sort();
0
var arr = array.sort(function(a,b){ return a.split(' ')[0] < b.split(' ')[0]})
1
  • A sort comparison function needs to return a negative value, a positive value or zero, not a boolean value.
    – nnnnnn
    Commented Jun 5, 2012 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.