-3

So I found this neat implementation to sort a list based on data-attributes: jquery sort list based on data attribute value

The trouble I have is that my data attributes have varying length and mixed letters and numbers so the sorting falls a little short, here's an example based on the above solution:

<ul class="listitems">
  <li data-position="test3">Item 3</li>
  <li data-position="test2">Item 2</li>
  <li data-position="test1">Item 1</li>
  <li data-position="test4">Item 4</li>
  <li data-position="test23">Item 23</li>
  <li data-position="test35">Item 35</li>
  <li data-position="test33">Item 33</li>
</ul>

http://jsfiddle.net/ddLp14pp/1/

I'd like the ordering of the numbers to be incremental (1,2,3,4,25,33,35 etc), but I can't solve it and I can't find anything on here or google.

PS. The sorting is based on data-attribute because the <li> contains several <a> and <span>

Community
  • 1
  • 1
Nahaz
  • 103
  • 1
  • 4

1 Answers1

0

You need to sort numerically rather than alphabetically, so remove the word test and convert to a number, then compare. As so:

$(".listitems li").sort(sort_li).appendTo('.listitems');
function sort_li(a, b){
    return (+$(b).data('position').replace("test","")) <     (+$(a).data('position').replace("test","")) ? 1 : -1;    
}
Evan Knowles
  • 7,426
  • 2
  • 37
  • 71
  • I was a bit hasty so I forgot to mention it's not always "test" before the numbers, so I would need to do both. Nonetheless this answers the question I posed. – Nahaz Jan 23 '15 at 11:33