Mastering array sorting in JavaScript: a guide to the sort() function
Tags: javascript, development
Published: 2023-06-05 15:54:00

---
title: Mastering array sorting in JavaScript: a guide to the sort() function
published: true
description: The potential of sort() function in JavaScript.
date: 2023-06-05 15:54 UTC
tags: javascript, development
canonical_url: https://www.ma-no.org/en/programming/javascript/mastering-array-sorting-in-javascript-a-guide-to-the-sort-function
cover_image: https://www.ma-no.org/cache/galleries/contents-2286/960-400/mastering-array-sorting-in-javascript-imppng.webp
# Use a ratio of 100:42 for best results.
# published_at:  2023-06-05 15:54 +0000
---


<p>In this article, I will explain the usage and potential of the 
  <code>sort()
  </code> function in JavaScript.
</p>
&nbsp;
<p><strong>What does the 
  <code>sort()
  </code> function do?</strong>
</p>
&nbsp;
<p>The 
  <code>sort()
  </code> function allows you to sort the elements of an array object. It can sort the elements in either the default ascending order or according to a custom sorting function.
</p>
<p>By default, the function sorts the elements in ascending order based on their string Unicode values. It converts the elements to strings and then arranges them using Unicode values.
</p>
&nbsp;
<p><strong>What is Unicode?</strong>
</p>
&nbsp;
<p>Unicode is a standard that assigns a unique numeric value, known as a code point, to every character used in writing systems worldwide. It enables computers to handle and represent various languages, symbols, and tastes consistently.
</p>
<p>For example, in the English Latin alphabet:
</p>
<p>- U+0041 to U+005A represents the Latin capital letters (A-Z).
  <br />
  - U+0061 to U+007A represents the Latin small letters (a-z).
</p>
<p>So, for instance, the word "Apple" in the Latin alphabet (English) is represented in Unicode as:
</p>
<p>A: U+0041
</p>
<p>p: U+0070
</p>
<p>p: U+0070
</p>
<p>l: U+006C
</p>
<p>e: U+0065
</p>
<p>
</p>
&nbsp;
<h3><strong>How does 
  <code>sort()
  </code> utilize Unicode tastes?</strong>
</h3>
&nbsp;
<p>
  <br />
  The 
  <code>sort()
  </code> function employs a sorting algorithm to sort the array. It can use various sorting algorithms such as bubble sort, quicksort, heapsort, or mergesort, depending on factors like array size, data types, and optimization strategies implemented by the JavaScript engine.
</p>
<p>The JavaScript engine executes the code and is responsible for interpreting and running JavaScript programs. It can be part of web browsers, server-side JavaScript platforms, or standalone JavaScript runtime environments.
</p>
<p>Among the sorting algorithms mentioned, quicksort or its variations are commonly used for sorting arrays in JavaScript.
</p>
<p>If you're interested in learning more about the quicksort algorithm, you can check out resources like the W3Resource website.
</p>
<p>How to use the 
  <code>sort()
  </code> function in JavaScript
  <br />
  Now that we understand how 
  <code>sort()
  </code> works internally, let's see how to use it.
</p>
<p>To use the function, simply call 
  <code>{array}.sort()
  </code>. This will sort the elements in the default ascending order, as described earlier.
</p>
&nbsp;
<pre>
javascript
const tastes = [
"Margherita",
"Napoletana",
"Quattro Formaggi",
"Primavera",
"Marinara",
"Boscaiola",
"Bufala",
];
const sortedArray = tastes.sort();
// Output:
["Boscaiola", "Bufala", "Primavera", "Margherita", "Marinara", "Quattro Formaggi", "Napoletana"];
</pre>
&nbsp;
<p>As you can see in the example, the names of the tastes have been sorted in ascending order based on their Unicode representation.
</p>
<p>If you want to have them sorted in descending alphabetical order, you can chain the 
  <code>reverse()
  </code> function after 
  <code>sort()
  </code>. This will reverse the order of the elements once they have been sorted.
</p>
<p>
</p>
&nbsp;
<h3><strong>What about sorting numbers?</strong>
</h3>
&nbsp;
<p>
</p>
<p>Let's explore it:
</p>
&nbsp;
<pre>
const numbers = [9, 3, 12, 11, 40, 28, 5];
const sortedNumbers = numbers.sort();
console.log(sortedNumbers);
// Output:
[11, 12, 28, 3, 40, 5, 9];
</pre>
&nbsp;
<p>Mmmmmmh ,the result is not sorted in the expected order. Why?
</p>
<p>Well, remember when I mentioned that the default sorting method uses Unicode character sorting after converting the elements to strings? That's the reason. The numbers are converted to their string equivalents and then sorted based on Unicode values.
</p>
<p>As a consequence, all the numbers starting with '1' come before any other numbers. Therefore, '11' is sorted before '3', and so on.
</p>
<p>Let's examine the Unicode values for these numbers:
</p>
<p>- 11: U+0031 U+0031
  <br />
  - 12: U+0031 U+0032
  <br />
  - 28: U+0032 U+0038
  <br />
  - 3: U+0033
  <br />
  - 40: U+3034 U+0030
  <br />
  - 5: U+3035
  <br />
  - 9: U+3039
</p>
<p>As you can see, if we sort based on Unicode tastes, the comparison between '1' and '3' results in '0031' being less than '0033'. Consequently, the numbers starting with '1' will be pushed to the front of the array.
</p>
<p>You might find this behavior annoying. But don't worry, there's a solution: using custom compare functions.
</p>
<p>
</p>
&nbsp;
<h3><strong>How to Use a Custom Sort Function</strong>
</h3>
&nbsp;
<p>
</p>
<p>As mentioned earlier, the sort() function can accept a custom comparison function as an argument.
</p>
&nbsp;
<pre>
sort(compareFn?: ((a: never, b: never) =&gt; number) | undefined): never[]
</pre>
&nbsp;
<p>The comparison function is used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they are equal, and a positive value otherwise. If the comparison function is omitted, the elements are sorted in ascending ASCII character order.
</p>
<p>For example:
</p>
&nbsp;
<pre>
[11, 2, 22, 1].sort((a, b) =&gt; a - b);
</pre>
&nbsp;
<p>This code sorts an array in place. The method mutates the array and returns a reference to the same array.
</p>
<p>So, what does all of this mean?
</p>
<p>The custom comparison function has specific expectations. It requires you to return certain values:
</p>
<p>- -1: if the value on the left is less than the value on the right.
  <br />
  - 0: if the value on the left is equal to the value on the right.
  <br />
  - 1: if the value on the left is greater than the value on the right.
</p>
<p>In simpler terms, returning -1 moves the item to the left (before the compared value), returning 0 keeps it in place, and returning 1 moves the item to the right (after the compared value).
</p>
<p>Now let's explore some examples to understand how it works.
</p>
<p>Referring to the previous example where we struggled to sort an array of numbers, we can fix this by using a custom comparison function:
</p>
&nbsp;
<pre>
const numberSortFn = (a, b) =&gt; {
if (a &lt; b) {
return -1;
} else if (a === b) {
return 0;
} else {
return 1;
}
};
const numbers = [9, 3, 12, 11, 40, 28, 5];
const sortedNumbers = numbers.sort(numberSortFn);
console.log(sortedNumbers);
// Output:
[3, 5, 9, 11, 12, 28, 40];
</pre>
&nbsp;
<p>As you can see, the array is now sorted in numerical ascending order as we expected. The reason it works differently is because the less than operator now compares the values as numbers rather than strings.
</p>
<p>
</p>
&nbsp;
<h3><strong>Other Uses of the Custom Comparison Function</strong>
</h3>
&nbsp;
<p>
</p>
<p>In addition to sorting arrays of numbers, you can also utilize the custom comparison function to sort objects based on their properties. Let's explore an example of sorting an array of objects (books) based on their year of publication.
</p>
&nbsp;
<pre>
const books = [
{ title: "Book A", year: 2010 },
{ title: "Book B", year: 2005 },
{ title: "Book C", year: 2018 },
];
const booksSortedByYearAsc = books.sort((a, b) =&gt; a.year - b.year);
console.log(booksSortedByYearAsc);
// Output:
[
{ title: "Book B", year: 2005 },
{ title: "Book A", year: 2010 },
{ title: "Book C", year: 2018 },
];
```
</pre>
&nbsp;
<p>In this example, we provide a custom comparison function that compares the objects based on their `.year` property. By subtracting `b.year` from `a.year`, we can achieve ascending order sorting based on the year of publication.
</p>
<p>This technique allows you to sort objects in arrays based on any property you choose. You simply need to modify the comparison function accordingly to compare the desired properties.
</p>
<p>By utilizing custom comparison functions, you gain flexibility in sorting arrays of various data types and objects based on specific criteria.
</p>
<p>
</p>
&nbsp;
<h3><strong>Sorting based on the content of the string</strong>
</h3>
&nbsp;
<p>
</p>
<p>Let's take our sorting capabilities a step further. Imagine we have a list of attendees at a seminar, and we want to generate a register. However, we want to prioritize the doctors and have them listed at the top, as they are the keynote speakers.
</p>
<p>We can achieve this using a custom comparison function:
</p>
&nbsp;
<pre>
const names = ["Mike Smith", "Dr. Johnson", "John Doe", "Dr. Williams"];
names.sort((a, b) =&gt; {
if (a.startsWith("Dr.") &amp;&amp; !b.startsWith("Dr.")) {
return -1;
} else if (!a.startsWith("Dr.") &amp;&amp; b.startsWith("Dr.")) {
return 1;
} else {
return a.localeCompare(b); // sort alphabetically
}
});
console.log(names);
// Output:
["Dr. Johnson", "Dr. Williams", "John Doe", "Mike Smith"];
</pre>
&nbsp;
<p>In this example, we define a custom comparison function that checks if a string starts with "Dr." or not. If the first string starts with "Dr." and the second one does not, we return -1, indicating that the first string should be placed before the second string in the sorted array. Conversely, if the first string does not start with "Dr." and the second one does, we return 1 to indicate the opposite order.
</p>
<p>For cases where neither string has "Dr." at the beginning, we resort to using the `localeCompare` function. This function performs an alphabetical comparison using Unicode values, similar to the default behavior discussed earlier in this article.
</p>
<p>By incorporating custom comparison logic, you can prioritize specific patterns or values in your sorting process, enabling you to achieve more specialized sorting results based on the content of the strings.
</p>
<p>
</p>
&nbsp;
<h3><strong>Strings of Numbers and Letters</strong>
</h3>
&nbsp;
<p>
</p>
<p>Suppose you have an array that contains a mixture of numbers and letters, and you want to sort it in a specific way. Your goal is to have the numbers appear before the letters, and within each group, you want the elements to be sorted numerically and alphabetically, respectively. Here's how you can achieve that using a custom comparison function:
</p>
&nbsp;
<pre>
const items = ["b", "3", "a", "2", "c", "1"];
</pre>
<p>items.sort((a, b) =&gt; { const aIsNumber = !isNaN(a); const bIsNumber = !isNaN(b); if (aIsNumber &amp;&amp; !bIsNumber) { return -1; // Numbers should be sorted before letters } else if (!aIsNumber &amp;&amp; bIsNumber) { return 1; // Letters should be sorted after numbers } else if (aIsNumber &amp;&amp; bIsNumber) { return a - b; // Sort numbers numerically } else { return a.localeCompare(b); // Sort letters alphabetically } }); console.log(items) // Output: ["1", "2", "3", "a", "b", "c"];
</p>
&nbsp;
<p>In this example, we first determine whether each value is a number or not using the 
  <code>isNaN()
  </code> function. By checking if the negation of 
  <code>isNaN()
  </code> is `true`, we can identify if the value is a number.
</p>
<p>Based on this information, we apply the following logic:
</p>
<p>- If `a` is a number and `b` is not a number, we return -1 to indicate that numbers should be sorted before letters.
  <br />
  - If `a` is not a number and `b` is a number, we return 1 to indicate that letters should be sorted after numbers.
  <br />
  - If both `a` and `b` are numbers, we subtract `b` from `a` (`a - b`). This allows us to sort the numbers numerically by comparing the numeric values.
  <br />
  - If none of the above conditions are met, we resort to using `localeCompare()` to sort the letters alphabetically.
</p>
<p>By incorporating this custom comparison logic, we can achieve the desired sorting order, where numbers appear before letters, and within each group, the elements are sorted numerically and alphabetically, respectively.
</p>
&nbsp;
<h3>
</h3>
&nbsp;
<h3><strong>Strings of Numbers and Letters</strong>
</h3>
&nbsp;
<p>
</p>
<p>Suppose you have an array that contains a mixture of numbers and letters, and you want to sort it in a specific way. Your goal is to have the numbers appear before the letters, and within each group, you want the elements to be sorted numerically and alphabetically, respectively. Here's how you can achieve that using a custom comparison function:
</p>
&nbsp;
<pre>
const items = ["b", "3", "a", "2", "c", "1"];
items.sort((a, b) =&gt; {
const aIsNumber = !isNaN(a);
const bIsNumber = !isNaN(b);
if (aIsNumber &amp;&amp; !bIsNumber) {
return -1; // Numbers should be sorted before letters
} else if (!aIsNumber &amp;&amp; bIsNumber) {
return 1; // Letters should be sorted after numbers
} else if (aIsNumber &amp;&amp; bIsNumber) {
return a - b; // Sort numbers numerically
} else {
return a.localeCompare(b); // Sort letters alphabetically
}
})
// Output:
["1", "2", "3", "a", "b", "c"];
</pre>
&nbsp;
<p>In this example, we first determine whether each value is a number or not using the 
  <code>isNaN()
  </code> function. By checking if the negation of 
  <code>isNaN()
  </code> is `true`, we can identify if the value is a number.
</p>
<p>Based on this information, we apply the following logic:
</p>
<p>- If `a` is a number and `b` is not a number, we return -1 to indicate that numbers should be sorted before letters.
  <br />
  - If `a` is not a number and `b` is a number, we return 1 to indicate that letters should be sorted after numbers.
  <br />
  - If both `a` and `b` are numbers, we subtract `b` from `a` (`a - b`). This allows us to sort the numbers numerically by comparing the numeric values.
  <br />
  - If none of the above conditions are met, we resort to using `localeCompare()` to sort the letters alphabetically.
</p>
<p>By incorporating this custom comparison logic, we can achieve the desired sorting order, where numbers appear before letters, and within each group, the elements are sorted numerically and alphabetically, respectively.
</p>
<p>In the code snippet provided, there is a custom comparison function used to sort an array containing both numbers and letters. The logic is designed to prioritize sorting based on the type (number or letter) and then further refine the order within each group. Let's break down the logic step by step:
</p>
<ol>
  <li>
    <p>Checking if values are numbers: The 
      <code>isNaN()
      </code> function is used to check if a value is not a number. By negating the result using the logical NOT operator 
      <code>(!)
      </code>, 
      <code>aIsNumber
      </code> and 
      <code>bIsNumber
      </code> are set to true if the corresponding value is a number and false otherwise.
    </p>
  </li>
  <li>
    <p>Sorting numbers before letters: The first if statement checks if a is a number (
      <code>aIsNumber
      </code> is true) and b is not a number (
      <code>bIsNumber
      </code> is false). In this case, we return -1 to indicate that a should come before b in the sorted order.
    </p>
  </li>
  <li>
    <p>Sorting letters after numbers: The second if statement checks if a is not a number (
      <code>aIsNumber
      </code> is false) and b is a number (
      <code>bIsNumber
      </code> is true). Here, we return 1 to indicate that b should come after a in the sorted order.
    </p>
  </li>
  <li>
    <p>Sorting numbers numerically: The third if statement checks if both a and b are numbers (aIsNumber and 
      <code>bIsNumber
      </code> are both true). In this case, we perform a numeric comparison by subtracting b from a. The result of this subtraction determines the relative order of the numbers.
    </p>
  </li>
  <li>
    <p>Sorting letters alphabetically: If none of the previous conditions are met, it means both a and b are strings (letters). We then use the 
      <code>localeCompare()
      </code> function to perform an alphabetical comparison and determine the order of the letters.
    </p>
  </li>
</ol>
<p>By applying this custom comparison logic, the array items is sorted in the desired order. Numbers appear before letters, and within each group, the elements are sorted numerically and alphabetically, respectively. The resulting sorted array is 
  <code>["1", "2", "3", "a", "b", "c"]
  </code>.
</p>
<p>
</p>
&nbsp;
<h3>Explanation of Sorting in Descending Order
</h3>
&nbsp;
<p>
</p>
<p>In the code snippet provided, the goal is to sort an array of tastes in descending order. Instead of using the 
  <code>sort(compareFn)
  </code> approach, the 
  <code>sort(compareFn)
  </code> function is used with a custom comparison function to achieve the desired result. Let's break down the code:
</p>
&nbsp;
<pre>
javascript
const tastes = [
"Margherita",
"Napoletana",
"Quattro Formaggi",
"Primavera",
"Marinara",
"Boscaiola",
"Bufala",
];
const sortedArray = tastes.sort((a, b) =&gt; b.localeCompare(a));
console.log(sortedArray);
// Output:
["Quattro Formaggi", "Primavera", "Napoletana", "Margherita", "Marinara", "Bufala", "Boscaiola"]
</pre>
&nbsp;
<p>The 
  <code>sort()
  </code> function takes a comparison function as an argument, which defines the custom sorting logic. In this case, the comparison function 
  <code>(a, b) =&gt; b.localeCompare(a)
  </code> is used.
</p>
<p>By default, the 
  <code>localeCompare()
  </code> function compares strings in ascending alphabetical order. However, to achieve descending order, the comparison is inverted by comparing `b` to `a` instead of the usual `a` to `b`. This reversal of the operands ensures that the comparison is performed in the desired descending order.
</p>
<p>As a result, the array `tastes` is sorted in descending order, and the sorted array `sortedArray` contains the elements 
  <code>["Napoletana", "Quattro Formaggi", "Marinara", "Margherita", "Primavera", "Bufala", "Boscaiola"]`
  </code>.
</p>
<p>It's worth noting that this approach works specifically for sorting an array of strings. If you're sorting numbers or objects based on a specific property, the comparison logic will differ.
</p>
<p>When it comes to the performance of sorting arrays, there are several factors to consider, including the JavaScript engine, array size, and complexity of the custom sorting function. The performance can vary based on these factors.
</p>
<p>In general, the built-in 
  <code>sort()
  </code> method tends to be highly optimized by ECMAScript implementations, making it very efficient for most sorting scenarios. It utilizes internal algorithms that are designed to handle a wide range of use cases and perform well in various scenarios.
</p>
<p>On the other hand, using a custom comparison function with the 
  <code>sort(compareFn)
  </code> method introduces additional complexity to the sorting process. The execution time of the custom function can impact the overall performance, especially for large arrays or if the custom logic involves complex computations.
</p>
<p>In the example you provided, sorting an array of 100 words in ascending order, the 
  <code>sort(compareFn)
  </code> implementation was faster than the default 
  <code>sort()
  </code> method. However, when sorting in descending order, the 
  <code>sort(compareFn)
  </code> chaining was faster than the 
  <code>sort(compareFn)
  </code> approach.
</p>
<p>The difference in execution time between the two approaches may seem small (e.g., 6ms), but it can become more significant as the array size grows or when dealing with more complex sorting requirements.
</p>
<p>As a general guideline, it's recommended to use the default 
  <code>sort()
  </code> method whenever possible, as it is optimized and performs well for most use cases. Reserve the use of custom comparison functions for situations where you have specific and complex sorting requirements that cannot be achieved with the default sorting behavior.
</p>
<p>Ultimately, it's important to consider the trade-off between customization and performance when deciding which approach to use for sorting arrays.
</p>
<p>
</p>
&nbsp;
<h3>
</h3>
<p class="h3"><strong>Conclusion</strong>
</p>
&nbsp;
<p>That concludes the discussion on the JavaScript 
  <code>sort()
  </code> function. Throughout the article, we covered the basics of the 
  <code>sort()
  </code> function, delved into its inner workings, and explored various use cases and examples to illustrate its versatility. We also discussed some considerations and performance implications when working with the 
  <code>sort()
  </code> function.
</p>
<p>I'm glad you found the article helpful in gaining a better understanding of the 
  <code>sort()
  </code> function and its capabilities. If you have any more questions or need further assistance, feel free to ask. Additionally, you can follow me on Twitter at gWeaths to stay updated on any future articles or information.
</p>
<p>Thank you for your engagement, and happy coding!
</p>
<p>
</p>