Sorting Divs Using Jquery
Solution 1:
It's a casing issue try to sort your element ad ignore the case and using localCompare
function.
The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
Code:
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("a:first").text().toLowerCase().localeCompare($(b).find("a:first").text().toLowerCase());
});
Solution 2:
Really it's just about a proper function for sort. There's no sort for jQuery objects, it's basically using Array.prototype.sort. If you check on the documentation:
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
What you are doing is:
return $(a).find("a:first").text() > $(b).find("a:first").text();
Which depending on how sort does the comparison, true or false values could be casted to 1 or 0 but never -1.
There's an example on the MDN on how to work with it:
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic' },
{ name: 'Zeros', value: 37 }
];
items.sort(function (a, b) {
if (a.name > b.name) {
return1;
}
if (a.name < b.name) {
return -1;
}
// a must be equal to breturn0;
});
Visit the MDN page on Array.prototype.sort:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Post a Comment for "Sorting Divs Using Jquery"