toSorted

An array method that returns a sorted copy and leaves the original unchanged, unlike sort, which reorders the array in place.

In more detail

Sorting a prop or state array with sort mutates it and breaks purity; toSorted, or slice().sort(), sorts a copy. toSorted is part of ECMAScript 2023.

Example

const sorted = items.toSorted((a, b) => a.price - b.price);

Related terms

Taught in

References