Examples of sorting different types of javascript arrays

A few examples of how to sort different types of javascript arrays.

What sort does by default

Array.sort() sorts values as strings by default. This works well for strings, but not as well for sorting numbers.

Default sort for strings

const names = ['Mike', 'Joe', 'Fred', 'Dan'];
names.sort();
console.log(names);
// output: ["Dan", "Fred", "Joe", "Mike"]

You can see it sorts them alphabetically. Nice!

Default sort for numbers

How about for numbers:

const numbers = [2, 30, 45, 1, 100];
numbers.sort();
console.log(numbers);
// output: [1, 100, 2, 30, 45]

As you can see, it’s sorting them by strings still! Probably not what we expected

Custom sort for numbers

Let’s write our own custom sort to sort the numbers how we expected:

const numbers = [2, 30, 45, 1, 100];
numbers.sort(function(a, b) {
  if (a > b) {
      return 1
  } else {
      return -1
  }
});
// output: [1, 2, 30, 45, 100]

Much better! So what did we do there? Let’s break it down:

  • We passed a compare function to sort, which is an optional parameter
  • The compare function gives you access to two variables (a and b) which are meant to represent items to sort
  • Here are the rules for a and b:
    • Return value is greater than 0: sort b before a
    • Return value is less than 0: sort a before b
    • Return value is equal to 0: keep the order of a and b the same

Now that you get the idea, you can write much more robust sorting functions comparing a vs b, which could even be objects with properties.

For other javascript examples: https://www.mikesallese.me/tags/javascript