Course contentsShow
← JavaScript
Lesson 905 of 2,72320. Array Iteration and TransformationFree lesson

Creating Immutable Sorted Copies

Use toSorted (ES2023) or spread with sort to create a new sorted array without mutating the original.

Creating Immutable Sorted Copies

What you'll learn: How to sort arrays without changing the original by using toSorted() or the spread operator with sort().

The Problem with sort()

As you've learned, the sort() method mutates the original array. Sometimes you want a sorted version but need to keep the original intact—perhaps you're displaying data in multiple places, or the original order matters for other operations.

Two Solutions

1. Using toSorted() (ES2023)

The toSorted() method returns a new sorted array, leaving the original untouched:

const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.toSorted((a, b) => a - b);

console.log(numbers); // [3, 1, 4, 1, 5] — unchanged!
console.log(sorted);  // [1, 1, 3, 4, 5]

2. Using Spread with sort()

Before toSorted() existed, developers used the spread operator to create a copy first:

const numbers = [3, 1, 4, 1, 5];
const sorted = [...numbers].sort((a, b) => a - b);

console.log(numbers); // [3, 1, 4, 1, 5] — unchanged!
console.log(sorted);  // [1, 1, 3, 4, 5]

Which Should You Use?

Use toSorted() when available—it's more explicit about intent and pairs with other immutable methods like toReversed() and toSpliced(). Use the spread approach if you need broader browser support or are working in older environments.

Real-World Example

const scores = [85, 92, 78, 95];
const ranked = scores.toSorted((a, b) => b - a); // descending

console.log("Original:", scores);  // [85, 92, 78, 95]
console.log("Ranked:", ranked);    // [95, 92, 85, 78]

Key Takeaway: Use toSorted() or [...array].sort() when you need a sorted copy while preserving the original array—essential for immutable programming patterns.