Sorting Lists
Sorting lists arranges list items in a chosen order. The order can be alphabetical or numeric.
Numbers in order
Subtraction puts the numbers in order.
const numbers = [3, 1, 2];
const ordered = [...numbers].sort((a, b) => a - b);
return <p>{ordered.join(', ')}</p>;Names in order
Sort with no compare function orders the names.
const names = ['Mia', 'Ada', 'Zoe'];
const ordered = [...names].sort();
return <p>{ordered.join(', ')}</p>;Example
import { useState } from 'react';
export default function App() {
const [names] = useState(['Mia', 'Zoe', 'Ada']);
const ordered = [...names].sort();
return (
<ul>
{ordered.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
}
Key points
- A list is an array of items rendered with map.
- The sort method orders the items in an array.
- A compare function tells sort how two items compare.
- Numbers sort with subtraction in the compare function.
- Sort with no compare function orders strings alphabetically.
In this example, the names state value holds three names. Three dots copy the names into a new array. Sort orders the copy alphabetically. Map renders one list item per name. The key is the name itself. The list shows Ada, Mia, and Zoe in that order.
Note
Sort changes the array it runs on, so copy the array first.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line sorts a copy of the numbers array in numeric order?