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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay