JS Array Sort

JavaScript Array Sort Methods

JavaScript provides built-in methods to sort the elements of an array. Understanding how these methods work is crucial, as their default behavior can sometimes be surprising.


1. The sort() Method

The sort() method sorts the elements of an array in place (meaning it modifies the original array) and returns the sorted array.

By default, sort() sorts values as strings. This works well for strings ("Apple" comes before "Banana").

Sorting an Array of Strings

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]


2. The Problem with Sorting Numbers

Because sort() treats elements as strings by default, it can produce incorrect results when sorting numbers. For example, "25" is greater than "100" alphabetically because "2" is greater than "1".

Incorrect Numeric Sort

const points = [40, 100, 1, 5, 25, 10];
points.sort();

console.log(points); // [1, 10, 100, 25, 40, 5] (Incorrect!)

The Solution: The Compare Function

To sort numbers correctly, you must provide a compare function as an argument to the sort() method.

The compare function should return a negative, zero, or positive value, depending on the arguments: function(a, b){return a - b}

Correct Numeric Sort (Ascending)

const points = [40, 100, 1, 5, 25, 10];

// Sort ascending points.sort(function(a, b){return a - b});

console.log(points); // [1, 5, 10, 25, 40, 100]

To sort in descending order, simply reverse the subtraction: function(a, b){return b - a}.


3. The reverse() Method

The reverse() method reverses the order of the elements in an array. It also modifies the array in place.

reverse() Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();

console.log(fruits); // ["Mango", "Apple", "Orange", "Banana"]

You can combine sort() and reverse() to easily achieve a descending sort for strings.


Exercise

?

How do you correctly sort the array `[10, 2, 1]` in ascending numerical order?