JavaScript Sorting Arrays


Sorting an Array

The sort() method arranges the elements in an array in alphabetical order.


Reversing an Array

The reverse() method changes the order of items in a array so that they go in the opposite direction.

You can use it to arrange an array from highest to lowest.


Numeric Sort

The sort() function, by default, arranges values as if they were words or text.

This is effective with text (Apple appears before Banana).

But, if you sort numbers like they are words, 25 is considered greater than 100 because the digit 2 is greater than 1.

Due to this issue, the sort() method will not give the right outcome when sorting numbers.

You can solve this issue by supplying a comparison function.

Apply the same technique to arrange an array in descending order:


The Compare Function

The compare function is used to create a different way to arrange things.

The compare function needs to give back a number that can be negative, zero, or positive, based on the arguments it receives.

function(a, b){return a - b}

When the sort() function checks two items, it uses a comparison function to decide how they should be ordered based on whether the result is negative, zero, or positive.

When the outcome is less than zero, 'a' is arranged ahead of 'b'.

If the outcome is good, b comes before a in the sorting order.

If the result is 0, it means that the order of the two values remains the same; there are no changes made in their sorting order.

Example:

The compare function looks at pairs of values in the array, two at a time, using (a, b).

When you compare the numbers 40 and 100, the sort() method invokes a comparison function with the parameters 40 and 100.

The operation subtracts (a - b) from 40, which results in a negative value (-60). Therefore, when using the sort function, 40 will be considered lower than 100.

You can try out this piece of code to practice sorting numbers and letters, both numerically and alphabetically.


Sorting an Array in Random Order


The Fisher Yates Method

The code shown above, when using array.sort(), is not entirely correct. It may give preference to certain numbers over others.

One commonly accepted approach is the Fisher Yates shuffle, which was first used in data science way back in 1938!

In JavaScript the method can be translated to this:


Find the Lowest (or Highest) Array Value

No ready-made functions exist to discover the highest or lowest value in an array.

Once you've arranged an array in a particular order, you can use the array's index to find both the largest and smallest values.

Sorting ascending:

Sorting descending:

Sorting an entire array is not very efficient if you just need to find the biggest or smallest number.


Using Math.max() on an Array

You can utilize the Math.max.apply method to locate the largest number within an array.

The code Math.max.apply(null, [1, 2, 3]) does the same thing as Math.max(1, 2, 3).


Using Math.min() on an Array

You can employ the Math.min.apply function to locate the smallest number within an array.

The Math.min.apply(null, [1, 2, 3]) does the same thing as Math.min(1, 2, 3).


Sorting Object Arrays

JavaScript arrays often contain objects:

Example

const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

Even if things in a list have different types, you can still use the sort() method to arrange them in order.

The solution is to write a compare function to compare the property values:

Comparing text characteristics can be a bit tricky:


Stable Array sort()

In 2019, changes were made to the Array's 'sort()' method, which were revised.

Prior to 2019, the rules allowed for sorting methods that were not very reliable, like QuickSort.

After ES2019, browsers must use a stable sorting algorithm:

When you organize items based on a particular value, it's important to ensure that items with the same value stay in their original order relative to each other.

In the provided example, when we sort items based on their prices, the outcome should not rearrange the names to different positions, like this:

X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110