HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Array Sort

Sorting is one of the most common operations performed on arrays. JavaScript provides two fundamental methods for organizing your data: sort() for ordering elements and reverse() for flipping the order.


Sorting Alphabetically

By default, the sort() method sorts values as strings in alphabetical and ascending order.

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

Numeric Sort (The Big Catch)

If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". Because of this, the standard sort() method will produce an incorrect result when sorting numbers.

The Compare Function

To sort numbers correctly, you must pass a compare function into the sort() method.

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); 
// Result: [1, 5, 10, 25, 40, 100]

How it works:

  • If the result of a - b is negative, a is sorted before b.
  • If the result is positive, b is sorted before a.
  • If the result is 0, no changes are made.

Sorting Objects

Arrays often contain objects. You can use the compare function to sort objects by a specific property.

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

cars.sort(function(a, b){return a.year - b.year});
Warning: The sort() method overwrites the original array. If you want to keep the original array unchanged, use the modern (ES2023) toSorted() method instead.

Stable Sorting (ES2019+)

Since ES2019, JavaScript's sorting algorithm (Timsort) is stable. This means that elements with equal values will stay in their original relative order after sorting.


Key Points to Remember

  • Default sort() is for alphabetical strings
  • Always use a compare function for numeric sorting
  • sort() modifies the original array (mutates data)
  • Use reverse() to flip the current order of an array
  • For modern non-mutating sorts, use toSorted() (ES2023)
  • Use Math.random() - 0.5 in a compare function for a "random" sort (shuffling)