utils
Code

sort

Common ways to sort arrays in JavaScript — strings, numbers, and dates — with ascending and descending examples.

Sorting Arrays

Sorting in JavaScript is done with Array.prototype.sort.
You can customize the comparator to handle strings, numbers, and dates.

Strings


const fruits = ["banana", "apple", "cherry"];
 
fruits.sort((a, b) => a.localeCompare(b));
// ["apple", "banana", "cherry"]

Numbers


const numbers: number[] = [42, 5, 19, 100];
 
numbers.sort((a, b) => a - b);
// [5, 19, 42, 100]

Dates


const dates: string[] = ["2021-05-10", "2019-01-01", "2023-03-15"];
 
dates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
// ["2019-01-01", "2021-05-10", "2023-03-15"]