liveBook · Manning

Tosorted

As explained in Secrets of the JavaScript Ninja, Third Edition

The toSorted method returns a sorted copy of an array without modifying the original array.

Need a sorted array without changing the order of the original? `toSorted` works like `sort`, but returns a sorted copy instead of modifying the array it was called on. section 10.1.4

Keep the original order

`const numbers = [3, 1, 2]; const sorted = numbers.toSorted((a, b) => a - b);` Now `sorted` is `[1, 2, 3]`, while `numbers` remains `[3, 1, 2]`. section 10.1.4

The distinction matters when assigning the result: `const sorted = numbers.sort(...)` does not preserve `numbers`. `sort` modifies the original array and returns that same array. Before `toSorted`, the usual workaround was to duplicate the array, then sort the duplicate. `toSorted` provides that non-mutating choice directly. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the non-mutating behavior by contrasting it with sort; does not detail implementation internals.
Examples
Contrasts sorting an array of named objects with a reusable Intl.Collator against preserving the original with toSorted.
What it assumes
Assumes familiarity with JavaScript arrays; explains why assigning sort’s return value does not protect the original.
What you can do after
Apply it via JavaScript’s toSorted method to obtain sorted results without changing the input array.
How it connects
Connects to Array.sort, sorting comparators, array copying, and Intl.Collator.

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.