Day 10 of #100DaysOfCode!

Today's progress

I worked on the sort() method from freeCodeCamp.

What I learned

The sort() method changes the position of elements in an array in ascending order (A-Z) and returns in the original array.

Here's an example using the sort() method on an array of names.

let names = ["Jack", "Christian", "Robin", "Billy", "Terry", "Michael"]

names.sort();

console.log(names)
//output: ["Billy", "Christian", "Jack", "Michael", "Robin", "Terry"]

You'll see that the array of names is now in alphabetical order.

Simple enough, right? When it comes to strings, yes. But not numbers. Numbers are a little trickier and requires an additional function to work with.

Working with numbers

When it comes with working with numbers. The sort() method does not order them properly. Here's an example.

let numbers = [12, 1, 5, 3, 23]

numbers.sort()

console.log(numbers)
//output: [1, 12, 23, 3, 5]

Now, obviously that does not look like a sorted array of numbers. This is because sort() sorts elements alphabetically.

The above example does in fact work applying that A=1, B=2, C=3, D=4, E=5

Applying the alphabet to the numbers. The above example would look like this and you will see that the numbers are alphabetically sorted.

//  ["AB", "A", "E", "C", "BC"]
let numbers = [12, 1, 5, 3, 23]

numbers.sort()

console.log(numbers)
// ["A", "AB", "BC", "C", "E"]
//output: [1, 12, 23, 3, 5]

But of course we do not want our numbers to be sorted alphabetically but rather from smallest to largest.

Solving the issue with numbers

In order to help solve the sort() method issue with numbers. We need to use it with a compare function. Where it will compare two sets of elements compareFunction(a, b).

Here are some following rules worth noting when working with sort():

  1. if compare(a,b) is less than zero, the sort() method sorts a to lower index than b. Meaning, a comes first.

  2. if compare(a,b) is greater than zero, the sort() method sorts b to a lower index than b. So, b will come first.

  3. if compare(a,b) returns zero then the sort() method considers both a and b to be equal and the position of the elements remain unchanged.

Using the same array of numbers from earlier. Let's go ahead and use the sort() method along with the compareFunction(a,b)

let numbers = [12, 1, 5, 3, 23]

function sortNumbers(arr){
    return arr.sort(function(a, b){
        if(a > b) return 1
        if(a < b) return -1
        return 0;
    })
}

console.log(sortNumbers(numbers));
//output: [1, 3, 5, 12, 23]

Simply put

Using sort() method can be a useful tool to sort elements in an array in ascending order. However, its important to note that when using sort() that it orders elements alphabetically and that elements are compared as strings. This is where the compare function(a,b) comes in to properly compare elements and returning the value that meets the condition.

17