Sorting an array

Say we have an array of words, for example. We can alphabetically sort this array using the sort function.

let names = ["Aiden", "Tom", "Eryk", "Chris", "Jani", "Fraser", "Alfie"];
names.sort();
// output: (7) ["Aiden", "Alfie", "Chris", "Eryk", "Fraser", "Jani", "Tom"]

This is all well and good until we need to sort an array of numbers numerically. In this case, each number will be converted to a string and then sorted alphabetically resulting in stuff like this.

let numbers = [21634, 12, 632, 6874, 56, 1, 573];
numbers.sort();
// output: (7) [1, 12, 21634, 56, 573, 632, 6874]

In order to sort an array by numbers, we can use the following which utilises sort's compareFunction.

let numbers = [21634, 12, 632, 6874, 56, 1, 573]
numbers.sort(function(a, b){return a-b});
// output: (7) [1, 12, 56, 573, 632, 6874, 21634]

Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description