Module 6 · Lesson 4 of 424/32 in the course~18 min
Module lessons (4/4)
sort
Lesson preview5 hands-on exercises readyJavaScript Course · Module 6 — Functional array methods
Sort an array with a comparator; stable sort, copying via toSorted.
What you'll learn in this lesson
- Avoid the
arr.sort()bug without comparator (which converts everything to strings and sorts lexicographically!). - Write numeric
(a, b) => a - b, multi-criteria and string comparators (localeCompare). - Prevent accidental state changes by choosing
.toSorted(cmp)(ES2023) or[...arr].sort(cmp). - Take advantage of the stable ordering guaranteed by ES2019 to preserve the relative order with the same key.
Overview
Array.prototype.sort() hides two historical JavaScript pitfalls: it mutates the original array into place and, if called without a comparator, converts the elements to UTF-16 strings ([10, 2].sort() produces [10, 2] because '10' < '2'!).
Sections covered in this lesson
- 1Mental model: numerical comparator and
.toSorted()vs.sort() - 2Progressive examples
- 3Guided laboratory
- 4Check for understanding
Pro Lesson · Module 6 — Functional array methods
Unlock "sort" and the full JavaScript Course curriculum
Sort an array with a comparator; stable sort, copying via toSorted.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in JavaScript Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.