Sorting Lists in React
Learn how to sort arrays of strings, numbers, and objects before rendering them in React.
1. Introduction to Sorting Lists
Sorting means arranging items in a particular order, such as alphabetical order or numerical order. In React, we can use JavaScript array methods to sort data before displaying it.
The sort() method sorts the elements of an array. When working with React state or props, avoid modifying the original array directly. Create a copy before sorting.
[...array].sort() to sort a copy of an
array without changing the original array.
2. Sorting Strings Alphabetically
The sort() method can arrange strings in alphabetical order using JavaScript's default string sorting behavior.
Example
const courses = [
"React",
"Angular",
"JavaScript",
"ASP.NET Core"
];
const sortedCourses = [...courses].sort();
console.log(sortedCourses);
Expected Output
["ASP.NET Core", "Angular", "JavaScript", "React"]
The spread operator creates a copy of the courses array. The sort() method then sorts the copied array.
3. Sorting Numbers
By default, sort() compares array elements as strings. For numerical sorting, provide a comparison function.
Ascending Order
const numbers = [40, 5, 100, 25, 10];
const ascendingNumbers = [...numbers].sort(
(a, b) => a - b
);
console.log(ascendingNumbers);
Expected Output
[5, 10, 25, 40, 100]
Descending Order
const descendingNumbers = [...numbers].sort(
(a, b) => b - a
);
console.log(descendingNumbers);
Expected Output
[100, 40, 25, 10, 5]
a - b for ascending numerical order
and b - a for descending numerical order.
4. How Sorting Works
The following diagram shows how an unsorted array is copied, sorted, and prepared for rendering.
5. Sorting a List of Objects
When an array contains objects, we can sort the objects using one of their properties, such as name or price.
Example: Sorting Students by Name
function StudentList() {
const students = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Amit" },
{ id: 3, name: "Priya" }
];
const sortedStudents = [...students].sort(
(a, b) => a.name.localeCompare(b.name)
);
return (
<div>
<h2>Students in Alphabetical Order</h2>
<ul>
{sortedStudents.map((student) => (
<li key={student.id}>
{student.name}
</li>
))}
</ul>
</div>
);
}
export default StudentList;
Expected Output
Students in Alphabetical Order
- Amit
- Priya
- Rahul
6. Sorting Products by Price
We can sort products by their numerical price property to display the lowest-priced products first.
Example
function ProductList() {
const products = [
{ id: 1, name: "Monitor", price: 7000 },
{ id: 2, name: "Mouse", price: 500 },
{ id: 3, name: "Keyboard", price: 800 }
];
const sortedProducts = [...products].sort(
(a, b) => a.price - b.price
);
return (
<div>
<h2>Products by Price
Expected Output
Products by Price
- Mouse - ₹500
- Keyboard - ₹800
- Monitor - ₹7000
The comparison function sorts products from the lowest price to the highest price. Each product retains its original ID for use as a React key.
7. Sorting in Descending Order
To display the highest-priced product first, reverse the comparison function.
const sortedProducts = [...products].sort(
(a, b) => b.price - a.price
);
Expected Order
- Monitor - ₹7000
- Keyboard - ₹800
- Mouse - ₹500
8. Common Mistakes
Mistake 1: Sorting Numbers Without a Comparator
const numbers = [5, 100, 25, 10];
const result = [...numbers].sort();
Default sorting compares values as strings, so it does not guarantee the expected numerical order.
Correct Code
const result = [...numbers].sort(
(a, b) => a - b
);
// Result: [5, 10, 25, 100]
Mistake 2: Modifying the Original Array
products.sort(
(a, b) => a.price - b.price
);
sort() changes the array on which it is called. Avoid directly sorting arrays received through props or held in React state.
Correct Code
const sortedProducts = [...products].sort(
(a, b) => a.price - b.price
);
9. Practice Tasks
Complete these tasks to practise sorting lists in React.
Summary
Sorting lists in React can be performed using JavaScript's sort() method before rendering the data. A comparison function such as a - b sorts numbers in ascending order, while b - a sorts them in descending order. Object arrays can be sorted by properties such as name or price. Because sort() modifies the array on which it is called, creating a copy before sorting helps avoid unintended mutations of React state or props.