Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 998
Jamie Avatar asked Jul 19 '26 18:07

Jamie


1 Answers

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.

like image 101
the system Avatar answered Jul 22 '26 07:07

the system



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!