Javascript: Sort by Last Name

In this tutorial we’re going to learn at how to alphabetically sort a string of names, by last name, using javascript.

Let’s say you have a fantasy soccer app with a form that asks the user to submit a list of players they like. After the script gets the input, you want it to display the submitted players in a list, alphabetically ordered by last name.

We’ll use the sort() method and a custom compare function to get the job done.

First, before we sort by last name, let’s look at how the sort method works by default, by sorting our players by first name:

// First let's get the string of names
var submittedPlayers = "Lionel Messi, Cristiano Renaldo, Arjen Robben, Luis Suarez, Manuel Neuer, Gareth Bale"

// then we'll break the string into an array
var playersArray = submittedPlayers.split(", ");

// and sort the array
playersArray.sort();

// and finally, let's see what we've got
console.log(playersArray);

// ["Arjen Robben", "Cristiano Renaldo", "Gareth Bale", "Lionel Messi", "Luis Suarez", "Manuel Neuer"]

As you can see the default behaviour of sort() is to order the array alphabetically. In other words, the ordering is done one character at time starting from the left, similar to how your brain does it. This can get confusing when you need to sort an array of numbers, so let’s see how sort() works by default on integers:

var numberArray = [7, 5, 12, 4, 566];

numberArray.sort();

console.log(numberArray);
// [12, 4, 5, 566, 7] 

The 1 in 12 comes before 4, so it goes first, and the 5 in 566 comes before 7, so 566 goes before 7, but the first 6 in 566 puts it after the 5. Make sense?

So back to sorting by last name:


// first we need to create a compare function 
// to change how sorting works.

// Get two names to compare (a and b)
function compare (a,b) {

  //split the names as strings into arrays
  var aName = a.split(" ");
  var bName = b.split(" ");

  // get the last names by selecting
  // the last element in the name arrays
  // using array.length - 1 since full names
  // may also have a middle name or initial
  var aLastName = aName[aName.length - 1];
  var bLastName = bName[bName.length - 1];

  // compare the names and return either
  // a negative number, positive number
  // or zero.
  if (aLastName < bLastName) return -1;
  if (aLastName > bLastName) return 1;
  return 0;
}

// Now let's get the string of names
var submittedPlayers = "Lionel Messi, Cristiano Renaldo, Arjen Robben, Luis Suarez, Manuel Neuer, Gareth Bale"

// and break them into an array
var playersArray = submittedPlayers.split(", ");

// and sort the array using our compare function
playersArray.sort(compare);

// and finally, let's see what we've got
console.log(playersArray);

// you should get 
// ["Gareth Bale", "Lionel Messi", "Manuel Neuer", "Cristiano Renaldo", "Arjen Robben", "Luis Suarez"]

Okay so you might find that compare function a bit confusing. Where does the “a” and “b” come from? And why are we returning a 1, -1, or 0 to sort()?

Actually our compare function is just making explicit how sort() works under the hood and adds a bit of extra processing to get us the last name.

The sort() method cycles through the array comparing 2 elements at a time ( ex. “Luis Suarez”, “Manuel Neuer”) and deciding which one goes first. It then assigns a value to this comparison. If the first element should be after the second alphabetically (as it should here), it will return -1 (or any negative integer) and flip the order (“Manuel Neuer”, “Luis Suarez”). If it’s prior, it will return a 1 (or any positive integer) and not flip and if it’s the same it will return 0 and do nothing.

So, if you’re going to use sort() for anything other than sorting an array of strings alphabetically, make sure to write your own compare function that compares pairs of elements and returns a negative number, positive number or zero. Before we finish, let’s see how to sort integers so that we get the result we want (smallest to largest):


function compare(a, b) {
 // return a negative number
 // if a is less than b
 // positive number is greater than b
 // and 0 if they are the same
 return a-b;
}

var numberArray = [7, 5, 12, 4, 566];

numberArray.sort(compare);

console.log(numberArray);
// [4, 5, 7, 12, 566] 

Happy sorting!

2 thoughts on “Javascript: Sort by Last Name”

  1. Thx for the tut man – long time no talk. Although it runs counter to delving into the ins and outs of creating your own compare function which is ultimately far more useful – we would be remiss to not point out:

    playersArray.sort().reverse(); // 😉

    1. Thanks Scott! Yup .reverse() is really useful for reversing the order of the array.

      playersArray.sort(compare).reverse();
      
      // will give us
      // ["Luis Suarez", "Arjen Robben", "Cristiano Renaldo", "Manuel Neuer", "Lionel Messi", "Gareth Bale"]

      Technically, you could do the same thing in the compare function with

        if (aLastName < bLastName) return 1;
        if (aLastName > bLastName) return -1;
      

      but reverse() is more clear.

Leave a Reply