Custom JavaScript Array Sort

Just a simple bit of JavaScript code that I wanted to share. I had an array of strings representing playing cards and I wanted to sort them from King to Ace. This mix of alphanumeric characters required a custom sort function.

//Array of cards, the first character of the string represents the rank
var cards = ["K", "1", "J", "2", "7"];
cards.sort(function (a, b) {
    "use strict"; //needed to pass JSLint
    //custom sort order
    var order = "KQJ198765432A";
    if (order.indexOf(a[0]) > order.indexOf(b[0])) {
        return 1;
    } else if (order.indexOf(a[0]) < order.indexOf(b[0])) {
        return -1;
    } else {
        return 0;

This same logic could be used for other unique sorts; just change the order string to match the desired sort. If you want to sort an array of objects just change a[0] and b[0] to a.your_property_name[0] and b.your_property_name respectively.


No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *