Answered the same question here:
To repost:
After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...
- select all object via jquery selector
- convert to actual array (not array-like jquery object)
- sort the array of objects
- convert back to jquery object with the array of dom objects
Html
<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>
Plain jquery selector
$('.item');
[<div class="item" data-order="2">2</div>,
<div class="item" data-order="1">1</div>,
<div class="item" data-order="4">4</div>,
<div class="item" data-order="3">3</div>
]
Lets sort this by data-order
function getSorted(selector, attrName) {
return $($(selector).toArray().sort(function(a, b){
var aVal = parseInt(a.getAttribute(attrName)),
bVal = parseInt(b.getAttribute(attrName));
return aVal - bVal;
}));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
<div class="item" data-order="2">2</div>,
<div class="item" data-order="3">3</div>,
<div class="item" data-order="4">4</div>
]
See how getSorted() works.
Hope this helps!