DEV Community

Jessica Alves
Jessica Alves

Posted on

2

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).

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay