Jasper
Jasper

Reputation: 5238

Sort list numerally and then alphabetically using jQuery?

http://jsbin.com/aboca3/95/edit

Here is working example for separate numeral and alphabetical sort.

It works well, the problem is, it doesn't sort alphabetically items with equal <em> number.

E.g. it gives Salpinestars(58), Joe Rocket (58) on numeral sort. Should give reverse order.

I've tried to change items.sort(sortEm).prependTo(self); to items.sort(sortAlpha).sort(sortEm).prependTo(self);, but it doesn't work.

Any thoughts?

Upvotes: 0

Views: 1768

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272446

You can write one function to sort by two criterion.

// ORDER BY EmValue, LiMinusEmText

function sortBoth(a, b) {
    var aText = $(a).text().replace(/\(\d+\)\s*$/, "");      // chop off the bracket
    var bText = $(b).text().replace(/\(\d+\)\s*$/, "");      // and numbers portion
    var aValue = +$(a).find("em").text().replace(/\D/g, ""); // parse out em value
    var bValue = +$(b).find("em").text().replace(/\D/g, ""); // and convert to number
    if (aValue == bValue) {
        if (aText == bText) {
            return 0;
        }
        else if (aText < bText) {
            return -1;
        }
        else /*if (aText > bText)*/ {
            return 1;
        }
    }
    else {
        return aValue - bValue;
    }
}

// ORDER BY LiMinusEmText, EmValue

function sortBoth(a, b) {
    var aText = $(a).text().replace(/\(\d+\)\s*$/, "");      // chop off the bracket
    var bText = $(b).text().replace(/\(\d+\)\s*$/, "");      // and numbers portion
    var aValue = +$(a).find("em").text().replace(/\D/g, ""); // parse out em value
    var bValue = +$(b).find("em").text().replace(/\D/g, ""); // and convert to number
    if (aText == bText) {                                    // strings value same?
        return aValue - bValue;                              // then return a - b
    }
    else if (aText < bText) {
        return -1;
    }
    else /*if (aText > bText)*/ {
        return 1;
    }
}

Upvotes: 2

Denis Chmel
Denis Chmel

Reputation: 789

Use this sortEm():

function sortEm(a,b){
  var emA = parseInt($('em',a).text().replace(/[\(\)]/g,''));
  var emB = parseInt($('em',b).text().replace(/[\(\)]/g,''));
  if (emA == emB) { // sort alphabetically if em number are equal
    return sortAlpha(a,b);
  }
  return emA < emB ? 1 : -1;
}

Upvotes: 3

Related Questions