Saad Khan
Saad Khan

Reputation: 77

Unable to do sort on arrays

I am trying to sort an array of jquery objects by text.

var $divs = $("#"+menu +"> div");
var numOrderedDivs = $divs.sort(function (a, b) {
    return $(a).text() > $(b).text();
});
$("#"+menu).html(numOrderedDivs);

However I am seeing no changes

enter image description here

enter image description here

Upvotes: 0

Views: 53

Answers (2)

Akrion
Akrion

Reputation: 18525

Try using String.localeCompare in your sort:

var $divs = $("#"+menu +"> div");
var numOrderedDivs = $divs.sort(function (a, b) {
    return $(a).text().localeComrate($(b).text());
});
$("#"+menu).html(numOrderedDivs);

It:

... returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order

it also supports various options for comparisons which are quite handy.

Also Array.sort works with a comparer function which return value should be an integer as per the docs:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

and not a boolean like you have here: return $(a).text() > $(b).text();

localeCompare does that for you when used.

Upvotes: 1

Nitish Narang
Nitish Narang

Reputation: 4184

Try this ".localeCompare" for sorting strings

var numOrderedDivs = $divs.sort(function (a, b) {
    return $(a).text().localeCompare($(b).text()) // for sorting in increasing order
});

Upvotes: 0

Related Questions