Javascript sort function. Sort by First then by Second

I have an array of objects to sort. Each object has two parameters: Strength and Name

objects = []
object[0] = {strength: 3, name: "Leo"}
object[1] = {strength: 3, name: "Mike"}

I want to sort first by Strength and then by name alphabetically. I am using the following code to sort by the first parameter. How do I sort then by the second?

function sortF(ob1,ob2) {
  if (ob1.strength > ob2.strength) {return 1}
  else if (ob1.strength < ob2.strength){return -1}
  return 0;
};

Thanks for your help.

(I am using Array.sort() with the aforementioned sortF as the sort comparison function passed into it.)


Expand your sort function to be like this;

function sortF(ob1,ob2) {
    if (ob1.strength > ob2.strength) {
        return 1;
    } else if (ob1.strength < ob2.strength) { 
        return -1;
    }

    // Else go to the 2nd item
    if (ob1.name < ob2.name) { 
        return -1;
    } else if (ob1.name > ob2.name) {
        return 1
    } else { // nothing to split them
        return 0;
    }
}

A < and > comparison on strings is an alphabetic comparison.


This little function is often handy when sorting by multiple keys:

cmp = function(a, b) {
    if (a > b) return +1;
    if (a < b) return -1;
    return 0;
}

or, more concisely,

cmp = (a, b) => (a > b) - (a < b)

Which works because in javascript:

true - true // gives 0
false - false // gives 0
true - false // gives 1
false - true // gives -1

Apply it like this:

array.sort(function(a, b) { 
    return cmp(a.strength,b.strength) || cmp(a.name,b.name)
})

Javascript is really missing Ruby's spaceship operator, which makes such comparisons extremely elegant.


You could chain the sort order with logical OR.

objects.sort(function (a, b) {
    return a.strength - b.strength || a.name.localeCompare(b.name);
});

When I was looking for an answer to this very question, the answers I found on StackOverflow weren't really what I hoped for. So I created a simple, reusable function that does exactly this. It allows you to use the standard Array.sort, but with firstBy().thenBy().thenBy() style. https://github.com/Teun/thenBy.js

PS. This is the second time I post this. The first time was removed by a moderator saying "Please don't make promotional posts for your own work". I'm not sure what the rules are here, but I was trying to answer this question. I'm very sorry that it is my own work. Feel free to remove again, but please point me to the rule involved then.