Sorting Arrays

Reorder array items with sort and reverse.

Syntaxarr.sort((a, b) => a - b)

sort() reorders an array in place. By default it sorts as text, which surprises people with numbers.

Sorting numbers

Pass a compare function. (a, b) => a - b sorts ascending; (a, b) => b - a sorts descending.

reverse() flips the order of items.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Sort a product listing by price from lowest to highest when the user selects that filter.
  • Alphabetically sort a list of country names for a dropdown select element.
  • Order an array of event objects by their date property to show upcoming events first.

More examples

Alphabetical sort

Calls sort() with no comparator to sort strings alphabetically in place.

Example · js
const countries = ["Norway", "Argentina", "Japan", "Brazil"];
countries.sort();
console.log(countries); // ["Argentina", "Brazil", "Japan", "Norway"]

Numeric sort with comparator

Passes a comparator function to sort numbers in ascending order; without it, sort would compare as strings.

Example · js
const prices = [29.99, 9.99, 49.99, 14.99];
prices.sort((a, b) => a - b);
console.log(prices); // [9.99, 14.99, 29.99, 49.99]

Sort objects by property

Sorts an array of event objects by their date property by converting dates to timestamps in the comparator.

Example · js
const events = [
  { name: "Workshop", date: "2024-09-10" },
  { name: "Launch",   date: "2024-07-01" },
  { name: "Meetup",   date: "2024-08-15" }
];
events.sort((a, b) => new Date(a.date) - new Date(b.date));
console.log(events.map(e => e.name)); // ["Launch", "Meetup", "Workshop"]

Discussion

  • Be the first to comment on this lesson.
Sorting Arrays — JavaScript | SoundsCode