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. 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. 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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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!
1

All you need is to call sort on your Array:

array.sort();

Comments

0
var arr = array.sort(function(a,b){ return a.split(' ')[0] < b.split(' ')[0]})

1 Comment

A sort comparison function needs to return a negative value, a positive value or zero, not a boolean value.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.