JavaScript AcademyProfessional Engineering

Learning object 18 of 100

Array sorting laboratory

Sort numbers, strings and objects with and without a compare function, and see why the default sort surprises people.

Loading…

What it shows

Without a compare function, sort converts every item to a string and compares the text, so 100 comes before 25. A compare function returns a negative number to put a first, a positive number to put b first, and 0 to keep their order. sort changes the array in place; copy it first with [...arr] or use toSorted.

Guided experiment

  1. Sort [10, 1, 25, 3, 100] with the default. Explain the order.
  2. Choose (a, b) => b - a. What changed?
  3. Sort the product objects by price, then by name.

Predict

What does [10, 9, 1].sort() produce?

Related

Lessons: Lesson 28: Searching and sorting arrays

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-018.js in the companion repository.