Jamie
Jamie

Reputation: 379

Javascript sorting of multiple digit numbers

I have a ul that I'm trying to sort using javascript (or jQuery if easier or necessary):

<ul>
  <li>1 - 5 days</li>
  <li>11 - 15 days</li>
  <li>16 - 20 days</li>
  <li>6 days - 10 days</li>
</ul>

The order I'm hoping for is: 1 - 5 days, 6 days - 10 days, 11 - 15 days, 16 - 20 days.

Now, I could always change the single digit items so that 1 - 5 is 01 - 05, but aesthetically I'm hoping theres a way around that!

I've tried the process described in What is the easiest way to order a <UL>/<OL> in jQuery?, but it doesn't apply for this case where I have multiple digits mixed in with text.

If it helps as a starting point: http://jsfiddle.net/5gHet/

Thanks so much! Would really appreciate any ideas.

Upvotes: 3

Views: 2582

Answers (3)

vol7ron
vol7ron

Reputation: 42109

Fiddle

In addition to parseInt you can do a little regex:

var $items = $('ul li');
var regex_first_num = /(\d+)/;

$items.sort(function(a,b){
  var keyA = $(a).text().match(regex_first_num)[0] *1;
  var keyB = $(b).text().match(regex_first_num)[0] *1;
  return keyA > keyB;
});

$('#newlist').append($items.clone());

Upvotes: 0

David Kiger
David Kiger

Reputation: 1996

Split the string on spaces, and then get the first number.

var items = $('ul li').get();
items.sort(function(a,b){
  var strA = $(a).text().split(' ');
  var strB = $(b).text().split(' ');

  if (parseInt(strA[0]) < parseInt(strB[0])) return -1;
  if (parseInt(strA[0]) > parseInt(strB[0])) return 1;
  return 0;
});
var ul = $('ul');
$.each(items, function(i, li){
  ul.append(li);
});

Demo at: http://jsfiddle.net/5gHet/1/

Upvotes: 0

the system
the system

Reputation: 9336

Use parseInt to convert the string to the the first number that appears.

items.sort(function(a,b){
  var keyA = parseInt($(a).text(), 10);
  var keyB = parseInt($(b).text(), 10);

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});

FYI, if there were non-numeric/whitespace characters that came before the first number, parseInt() would return NaN, so you'd need to extract the number manually.

Upvotes: 3

Related Questions