
ReactJS
π€ Sorting arranges items in a specific orderβalphabetically, numerically, by date, or by any custom criteria. JavaScript's `sort()` method rearranges array elements in place.
Important: `sort()` modifies the original array. In React, always create a copy first with spread operator or `slice()`.
interface Student {
id: number;
name: string;
score: number;
}
function StudentList() {
const students: Student[] = [
{ id: 1, name: "Alice", score: 85 },
{ id: 2, name: "Bob", score: 92 },
{ id: 3, name: "Carol", score: 78 },
{ id: 4, name: "David", score: 88 }
];
// Ascending order (lowest to highest)
const sortedAsc = [...students].sort((a, b) => a.score - b.score);
// Descending order (highest to lowest)
const sortedDesc = [...students].sort((a, b) => b.score - a.score);
return (
<div>
<h2>Highest Scores</h2>
<ul>
{sortedDesc.map(student => (
<li key={student.id}>
{student.name}: {student.score}
</li>
))}
</ul>
</div>
);
}interface User {
id: number;
name: string;
email: string;
}
function UserList() {
const users: User[] = [
{ id: 1, name: "Zara", email: "zara@example.com" },
{ id: 2, name: "Alice", email: "alice@example.com" },
{ id: 3, name: "Bob", email: "bob@example.com" }
];
// Alphabetical order
const sorted = [...users].sort((a, b) =>
a.name.localeCompare(b.name) // Use localeCompare for proper string sorting
);
return (
<ul>
{sorted.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}interface Product {
id: number;
name: string;
price: number;
rating: number;
}
function ProductList() {
const [sortBy, setSortBy] = React.useState<"price" | "rating">("price");
const [direction, setDirection] = React.useState<"asc" | "desc">("asc");
const products: Product[] = [
{ id: 1, name: "Laptop", price: 999, rating: 4.5 },
{ id: 2, name: "Phone", price: 599, rating: 4.8 },
{ id: 3, name: "Tablet", price: 399, rating: 4.2 },
{ id: 4, name: "Watch", price: 199, rating: 4.6 }
];
// Create a copy and sort
const sorted = [...products].sort((a, b) => {
let comparison = 0;
if (sortBy === "price") {
comparison = a.price - b.price;
} else if (sortBy === "rating") {
comparison = a.rating - b.rating;
}
return direction === "asc" ? comparison : -comparison;
});
return (
<div>
<div style={{ marginBottom: "20px" }}>
<label>
Sort by:
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value as "price" | "rating")}
style={{ marginLeft: "10px" }}
>
<option value="price">Price</option>
<option value="rating">Rating</option>
</select>
</label>
<button
onClick={() => setDirection(direction === "asc" ? "desc" : "asc")}
style={{ marginLeft: "20px" }}
>
{direction === "asc" ? "β Ascending" : "β Descending"}
</button>
</div>
<ul>
{sorted.map(product => (
<li key={product.id}>
{product.name} - ${product.price} β {product.rating}
</li>
))}
</ul>
</div>
);
}interface Employee {
id: number;
name: string;
department: string;
salary: number;
}
function EmployeeList() {
const employees: Employee[] = [
{ id: 1, name: "Alice", department: "Engineering", salary: 120000 },
{ id: 2, name: "Bob", department: "Engineering", salary: 110000 },
{ id: 3, name: "Carol", department: "Sales", salary: 80000 },
{ id: 4, name: "David", department: "Sales", salary: 85000 }
];
// Sort by department first, then by salary
const sorted = [...employees].sort((a, b) => {
// First, compare departments alphabetically
if (a.department !== b.department) {
return a.department.localeCompare(b.department);
}
// If departments are the same, compare by salary
return b.salary - a.salary;
});
return (
<ul>
{sorted.map(employee => (
<li key={employee.id}>
{employee.name} ({employee.department}) - ${employee.salary}
</li>
))}
</ul>
);
}interface Event {
id: number;
name: string;
date: Date;
}
function EventList() {
const events: Event[] = [
{ id: 1, name: "Conference", date: new Date("2024-03-15") },
{ id: 2, name: "Workshop", date: new Date("2024-02-20") },
{ id: 3, name: "Meetup", date: new Date("2024-03-01") }
];
// Sort by date (newest first)
const sorted = [...events].sort((a, b) => b.date.getTime() - a.date.getTime());
return (
<ul>
{sorted.map(event => (
<li key={event.id}>
{event.name} - {event.date.toLocaleDateString()}
</li>
))}
</ul>
);
}<details><summary>π More Examples</summary>
interface Item {
id: number;
name: string;
order: number;
}
function DraggableList() {
const [items, setItems] = React.useState<Item[]>([
{ id: 1, name: "First", order: 1 },
{ id: 2, name: "Second", order: 2 },
{ id: 3, name: "Third", order: 3 }
]);
const moveUp = (index: number) => {
if (index === 0) return;
const newItems = [...items];
[newItems[index - 1], newItems[index]] = [newItems[index], newItems[index - 1]];
setItems(newItems);
};
const moveDown = (index: number) => {
if (index === items.length - 1) return;
const newItems = [...items];
[newItems[index], newItems[index + 1]] = [newItems[index + 1], newItems[index]];
setItems(newItems);
};
return (
<ul>
{items.map((item, index) => (
<li key={item.id} style={{ display: "flex", gap: "10px", marginBottom: "10px" }}>
<span>{item.name}</span>
<button onClick={() => moveUp(index)}>β Up</button>
<button onClick={() => moveDown(index)}>β Down</button>
</li>
))}
</ul>
);
}interface Person {
id: number;
name: string;
}
function PersonList() {
const people: Person[] = [
{ id: 1, name: "alice" },
{ id: 2, name: "Zara" },
{ id: 3, name: "bob" }
];
// Case-insensitive sorting
const sorted = [...people].sort((a, b) =>
a.name.toLowerCase().localeCompare(b.name.toLowerCase())
);
return (
<ul>
{sorted.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}interface Task {
id: number;
title: string;
priority: "low" | "medium" | "high";
completed: boolean;
}
function TaskManager() {
const [showCompleted, setShowCompleted] = React.useState(false);
const tasks: Task[] = [
{ id: 1, title: "Buy groceries", priority: "low", completed: true },
{ id: 2, title: "Fix bug", priority: "high", completed: false },
{ id: 3, title: "Review PR", priority: "medium", completed: false }
];
const priorityOrder = { high: 3, medium: 2, low: 1 };
const filtered = tasks.filter(task => showCompleted || !task.completed);
const sorted = [...filtered].sort((a, b) =>
priorityOrder[b.priority] - priorityOrder[a.priority]
);
return (
<div>
<label>
<input
type="checkbox"
checked={showCompleted}
onChange={(e) => setShowCompleted(e.target.checked)}
/>
Show completed
</label>
<ul>
{sorted.map(task => (
<li key={task.id}>
{task.title} - {task.priority}
{task.completed && " β"}
</li>
))}
</ul>
</div>
);
}</details>
| Sort Type | Method | Example |
|---|---|---|
| Numbers (ascending) | `.sort((a, b) => a - b)` | Scores, prices |
| Numbers (descending) | `.sort((a, b) => b - a)` | Ratings, counts |
| Strings (A-Z) | `.sort((a, b) => a.localeCompare(b))` | Names, titles |
| Dates (newest) | `.sort((a, b) => b.date - a.date)` | Events, posts |
| Multiple fields | Chain comparisons | Department, then salary |
| Case-insensitive | `.toLowerCase().localeCompare()` | Proper string sorting |
1. β Always create a copy with spread operator before sorting
2. β Use `localeCompare()` for proper string sorting, not direct comparison
3. β Subtract in reverse order for descending: `b - a` instead of `a - b`
4. β Keep sorted state when reordering is driven by user interaction
5. β Combine sort with filter for more powerful list management
6. β Use stable sort criteria that don't change between renders
7. β Sort by multiple fields by chaining comparisons
8. β For dates, use `.getTime()` or convert to comparable values
9. β Provide visual feedback for sort direction (arrows, icons)
10. β Remember stable keys remain the same even when items reorder
Learn how to handle dynamic lists where items are constantly being added and removed.
Challenge: Build a sortable list
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward