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.

3 Answers 3

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.

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

2 Comments

Just return keyA - keyB;
@Bergi: Yes, this is OP's code, so I kept the changes minimal, but that would be nicer.
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/

2 Comments

This would fail horribly if he really used 08 - 11 days
Not in the latest JS: developer.mozilla.org/en-US/docs/JavaScript/Reference/…, but point taken.
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());

Comments

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.