javascript / intermediate
Snippet
Immutable Sorting and Chunking of Collection State with Array toSorted
Standard `Array.prototype.sort()` mutates arrays in place, which violates React's immutability principles and can cause subtle rendering bugs. Modern JavaScript provides `Array.prototype.toSorted()`, which returns a brand new sorted shallow copy without altering the original array prop. Combining `toSorted()` with `Array.prototype.slice()` enables clean, immutable pagination and ordering pipelines directly during rendering.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function ProductCatalog({ items, sortKey, pageIndex, pageSize }) {const sortedItems = items.toSorted((a, b) => {if (typeof a[sortKey] === 'string') {return a[sortKey].localeCompare(b[sortKey]);}return a[sortKey] - b[sortKey];});const startIndex = pageIndex * pageSize;const currentPageItems = sortedItems.slice(startIndex, startIndex + pageSize);return (<ul>{currentPageItems.map((product) => (<li key={product.id}>{product.title} - ${product.price}</li>))}</ul>);}
react
Breakdown
1
const sortedItems = items.toSorted((a, b) => {
Creates an immutably sorted copy of the collection without mutating the input props array.
2
return a[sortKey].localeCompare(b[sortKey]);
Performs language-sensitive string comparison for deterministic alphabetical sorting.
3
const currentPageItems = sortedItems.slice(startIndex, startIndex + pageSize);
Extracts the subset of elements required for the active pagination window.