Sorting Lists
Sorting Lists
Sorting means rendering list items in a specific order, alphabetically, by date, by number, or by any custom comparator. In React, use .sort() before .map(). Important: always sort a copy of the array using [...array].sort() or array.slice().sort() because .sort() mutates the original array, which causes bugs with React state.
JSX
import { useState } from 'react'; const courses = [ { id: 1, title: 'SEO Mastery', enrolled: 320, date: '2024-03-10' }, { id: 2, title: 'React Basics', enrolled: 890, date: '2024-01-05' }, { id: 3, title: 'Advanced CSS', enrolled: 145, date: '2024-06-20' }, { id: 4, title: 'Node.js Crash', enrolled: 560, date: '2024-02-14' }, ]; function SortableCourses() { const [sortBy, setSortBy] = useState('title'); // ✅ Spread to copy — never mutate original state array const sorted = [...courses].sort((a, b) => { switch (sortBy) { case 'title': return a.title.localeCompare(b.title); // A → Z case 'enrolled': return b.enrolled - a.enrolled; // High → Low case 'date': return new Date(b.date) - new Date(a.date); // Newest first default: return 0; } }); return ( <div> <label>Sort by: </label> <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}> <option value="title">Title A→Z</option> <option value="enrolled">Most Enrolled</option> <option value="date">Newest First</option> </select> <ul> {sorted.map((c) => ( <li key={c.id}> {c.title} — {c.enrolled} students </li> ))} </ul> </div> ); } // Combining filter + sort + map in one chain: // const result = [...data].filter(x => x.active).sort(...).map(...)
Never Mutate State Arrays:Array.sort()modifies the original array in place. If your courses array comes from React state, sorting it directly is a mutation that can cause subtle bugs. Always create a copy first:[...courses].sort(...)orcourses.slice().sort(...).
