zdebruine
zdebruine

Reputation: 3807

JavaScript array sort-function for both numeric and alphanumeric string

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!

Upvotes: 0

Views: 1891

Answers (4)

wuqiang
wuqiang

Reputation: 1

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

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150020

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.

Upvotes: 2

Paul
Paul

Reputation: 141839

All you need is to call sort on your Array:

array.sort();

Upvotes: 1

Bergi
Bergi

Reputation: 664346

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

Upvotes: 3

Related Questions