Array.sort(): defining the sort order

alvesjessica

Jessica Alves

Posted on March 26, 2023

Array.sort(): defining the sort order

The sort() method in JavaScript

"The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.", according to MDN Documentation.

Defining the sort order

Let's say you want to sort some data, a list of users for example, based on the status of each user (if they're online or offline), and based on the alphabetical order of the user's first name and last name, in that order respectively.

type User = {
  firstName: string,
  lastName: string,
  status: 'online' | 'offline'
}

const users: User[] = [
  { firstName: 'Rafael', lastName: 'Nadal', status: 'online'},
  { firstName: 'Fernando', lastName: 'Alonso', status: 'offline'},
  { firstName: 'Daniel', lastName: 'Ricciardo', status: 'online'},
  { firstName: 'Daniel', lastName: 'Brühl', status: 'online'},
];
Enter fullscreen mode Exit fullscreen mode

To do that we can use an optional sort() parameter compareFn which takes a function as an argument to define the sort order. This function has two parameters (a and b) that take the two elements of comparison as arguments. The return value r depends on the comparison result between the elements, according to the following logic:

// r > 0 if a > b
// returns a number greater than zero if a > b

// r = 0 // a === b
// returns zero if a === b

// r < 0 // a < b
// returns a number less than zero if a < b
Enter fullscreen mode Exit fullscreen mode

So if we want to write a function to sort our list considering the two mentioned elements (status and alphabetical order), we could write something like this:

const sortUsersByStatusAndName = users.sort((a, b) => {
  if (a.status === b.status) {
    if (a.firstName === b.firstName) {
      return a.lastName.localeCompare(b.lastName);
    }
    return a.firstName.localeCompare(b.firstName);
  }
  if (a.status === 'online') {
    return -1;
  }
  return 1;
});

console.log(sortUsersByStatusAndName);

/* expected output:
[{
  "firstName": "Daniel",
  "lastName": "Brühl",
  "status": "online"
}, {
  "firstName": "Daniel",
  "lastName": "Ricciardo",
  "status": "online"
}, {
  "firstName": "Rafael",
  "lastName": "Nadal",
  "status": "online"
}, {
  "firstName": "Fernando",
  "lastName": "Alonso",
  "status": "offline"
}] 
*/
Enter fullscreen mode Exit fullscreen mode

Note that we want to sort by bringing first all the online users (in alphabetical order), and finally the offline users (in alphabetical order as well).

💖 💪 🙅 🚩
alvesjessica
Jessica Alves

Posted on March 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Array.sort(): defining the sort order
javascript Array.sort(): defining the sort order

March 26, 2023