Guide to JavaScript Array Sort Method

css-logo

JavaScript array is a data structure that can hold one or more elements. The JavaScript array is mostly used to store elements and to organize them, so the values can be sorted or searched efficiently. In JavaScript, an array can hold different types of elements (numbers, strings, etc), but it is good practice all of the elements in the array to be the same type, so we can easily organize them as we want.

One of the many important things about an array in JavaScript is to sort the elements stored in the array. To do the JavaScript array sort, we need to create an array and insert some elements in it. To sort the array we will use the sort() method that returns the sorted array as default with ascending order.

Sorting Array of Strings

Let's see how we can sort an array of strings.

//here we have declared and initialized an array with strings
const strings = ["B", "A", "D", "C"];
strings.sort();
console.log(strings); //output: ["A","B","C","D"]

As we see in our example above, the strings were sorted in alphabet order because the strings are sorted by comparing them in UTF-16 code units.

Note: UTF-16 is a character encoding format.

Sorting Array of Numbers

Let's see how we can sort an array of numbers.

//here we have declared and initialized an array with numbers
const numbers = [1, 20, 5, 300, 80, 1000];
numbers.sort();
console.log(numbers); //output: [1,1000,20,300,5,80]

As we see in our example above, the output is not what we have expected. Let's take a closet look at how the JavaScript array sort method is working. To sort the elements in the array, the sort() method casts every element to string and then compares the given strings to determine the correct order of the elements, and we got the output for compared string values. This way most of the time if we sort numbers using the sort method by default it is not what we want.

To compare the items as numbers we need to pass a compare function that have two arguments (a and b) and should return 1 if the first number is larger, 0 if they are equal, and -1 if the second number is larger. Let's create a comparison function for numbers.

function sortNumbers(a, b) {
  if (a > b) {
    return 1;
  } else if (b > a) {
    return -1;
  } else {
    return 0;
  }
}

Now let's call the sort method again, now with the comparison function sortNumbers() as argument.

const numbers = [1, 20, 5, 300, 80, 1000];
numbers.sort(sortNumbers); // output: [1,5,20,80,300,1000]

There is a much shorter way to write the comparison function.

numbers.sort((a, b) => a - b);

As you see now we have sorted the numbers as we expected. To do the sorting in descending order you need just to replace the -1 with 1 and the same 1 with -1. JavaScript array sort method is a great way to sort elements, the time and complexity of the sort method depends on the implementation.




#javascript

Author: Aleksandar Vasilevski |