Sort arrays by comparing two arguments

Sorting an array in JavaScript? There’s a method for that!

Writing a sorting algorithm can be pretty tricky! Fortunately in JavaScript, Array.prototype.sort is built-in to every array. All you need to provide is a function that takes 2 numbers and decides which one comes first.

Let’s first think of it in plain English. I want you to sort a group of numbers in ascending order. Or more plainly: given two numbers, pick the lower one and put it first. It doesn’t matter to me how you choose the numbers you compare as long as they all are sorted at the end.

This is very similar to using sort on Arrays. As developers we don’t need to worry about what sorting algorithm the JavaScript engine uses! We just need to provide a function that compares two elements in the array.

Imagine we want to sort an array [2,3,1] into ascending order [1,2,3] . Depending on the sorting algorithm, the iterations might look like this:

The first iteration, we compare 3 and 2. The second iteration we compare 1 and 3. Finally we compare 1 and 2. Each of these iterations we return either a 1 or a -1. These values indicate something to the sort algorithm:

A negative number indicates that the first argument should come before the second argument.

number indicates that the first argument should come before the second argument. A positive number indicates that the second argument should come before the first argument.

number indicates that the second argument should come before the first argument. Zero indicates the values are equal.

In code, we can write out this function explicitly with conditionals:

function sortAscending(a,b) {

if(a > b) {

return 1; // take b first

}

if(b > a) {

return -1; // take a first

}

return 0;

}

This takes two numbers a and b and compares them. Then it returns 1 or -1 to indicate their order relative to the other.

We can simplify this code when we recognize we can use any positive value to take the a first or any negative value to take b first.

function sortAscending(a,b) {

return a - b;

}

Why does this work? When a is greater than b this will return a positive number. When b is greater than a this will return a negative number. If they are equal, it will return 0. This is the same logic as the first function we wrote with conditionals!

All that’s left for us to use this in an array is provide the function to our array sort method:

const sorted = [2,3,1].sort(sortAscending); console.log(sorted); // [1,2,3]

Of course, this will work for bigger arrays too!

const sorted = [4,2,7,9,12,99,32,1,-1,3].sort(sortAscending); console.log(sorted); // [-1, 1, 2, 3, 4, 7, 9, 12, 32, 99]

Enjoy this Article?

Master using sort by trying out some challenging Code Exercises! Take them right from the comfort of your own web browser 🙂

Don’t forget to clap to let us know you enjoyed this! 👏👏👏

Follow us on Twitter🐦 or join us at ChainShot to go from zero programming experience to blockchain developer!