Categories
JavaScript

JavaScript sort method – part 1

We have already talked about JavaScript Arrays filter method and JavaScript Arrays map method, and today we are talking about JavaScript sort method.

.sort() method sorts data alphabetically and numerically either in ascending or descending order. By default .sort() is sorting data alphabetically in ascending order. This means that “Audi” comes before “BMW” (nothing new, really). Also, the default, and only, data type for .sort() is a string. This means it will not sort numbers or objects.

const arr = ['BMW', 'Mercedes', 'Audi', 'Citroen', 'Ferrari'];

arr.sort();

console.log(arr);
//Result:
//['Audi', 'BMW', 'Citroen', 'Ferrari', 'Mercedes']

If we provide an array with numbers, the JavaScript sort method will convert every number to a string, so we can get some pretty unexpected results.

const arr = [128, 1, 333, 1000, 10, 100];

arr.sort();
//Result: 
//[1, 10, 100, 1000, 128, 333]

As we can see in the example above numbers are not in the correct, expected, order. This is because a number is converted to UTF-16. Because of that “1000” comes before “100” in Unicode order.

How to sort numbers with JavaScript sort method

There is a way around this problem with numbers. .sort() will accept compare functions. This means that if we provide some function that will compare numbers, numbers will not be converted to strings.

Compare function accepts two parameters a and b (we can call them whatever we want). Those are two elements from the array (this is done automatically). This function can return negative, zero, or positive results.

const numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

//Result:
// [1, 2, 3, 4, 5]

numbers.sort(function(a, b) {
  return b-a;
});
console.log(numbers);

//Result:
// [5, 4, 3, 2, 1]


numbers.sort(function(a, b) {
  return b===a;
});
console.log(numbers);

//Result:
// [4, 2, 5, 1, 3]

As we can see in the example above the following rules are applied:

  1. if we use function like function(a,b) { a - b }, array will be sorted in ascending order.
  2. if we use function like function(a,b) { b - a }, array will be sorted in descending order.
  3. if we use function like function(a,b) { a === b }, array’s order will not change (Have in mind that .sort() mutates the original array).
  4. if we use function like function(a,b) { b === a }, array’s order will not change.

In our next text, we will cover how to order some other data types like objects.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like SQL vs NoSQL. A practical explanation like I am 5.