3

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.

Community
  • 1
  • 1
Jamie
  • 379
  • 1
  • 5
  • 22

3 Answers3

3

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.

the system
  • 9,244
  • 40
  • 46
0

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/

David Kiger
  • 1,958
  • 1
  • 16
  • 25
  • 1
    This would fail horribly if he really used `08 - 11 days` – Bergi Feb 23 '13 at 23:07
  • Not in the latest JS: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt#ECMAScript_5_Removes_Octal_Interpretation, but point taken. – David Kiger Feb 23 '13 at 23:13
0

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());
Community
  • 1
  • 1
vol7ron
  • 40,809
  • 21
  • 119
  • 172