Sorting Displayed Data in React JS
Topic: Sorting Displayed Data in React JS
Sorting displayed data is an important React JS concept used to arrange information in a specific order, such as alphabetical order, ascending price, descending marks, newest date, or highest rating. React applications commonly use JavaScript's sort() method to organize arrays and React state to let users change the displayed order through buttons, dropdowns, and other controls.
1. What Is Sorting Displayed Data?
Sorting displayed data means arranging a collection of items according to a selected rule. The rule determines which item appears first, second, third, and so on.
For example, an e-commerce website may display products from lowest to highest price, while a student management system may arrange students alphabetically by name or from highest to lowest marks.
Examples of Sorting
- Alphabetical sorting: Arrange names from A to Z or Z to A.
- Numerical sorting: Arrange prices, marks, ages, or quantities in ascending or descending order.
- Date sorting: Display the newest or oldest records first.
- Rating sorting: Display products with the highest or lowest ratings first.
- Priority sorting: Arrange tasks according to their importance.
- Custom sorting: Arrange records according to a rule defined by the application.
2. Why Is Sorting Important in React?
- Helps users find relevant information quickly.
- Improves the organization of large data collections.
- Creates a better user experience in product listings and dashboards.
- Makes it easier to compare prices, marks, dates, and ratings.
- Allows users to change how information is displayed.
- Supports dynamic interfaces using React state.
- Helps build practical features such as sortable tables, product catalogs, and employee directories.
3. Understanding the JavaScript sort() Method
The JavaScript sort() method arranges the elements of an array according to a comparison function. It modifies the original array, so when sorting an array stored in React state, you should copy the array before sorting it.
Syntax
array.sort((a, b) => {
return comparisonResult;
});
The comparison function determines the relative order of two items:
- A negative result places
a before b.
- A positive result places
a after b.
- A zero result indicates that the items are equal for the comparison.
Example: Sorting Numbers
const numbers = [40, 10, 30, 20];
const ascending = [...numbers].sort((a, b) => a - b);
const descending = [...numbers].sort((a, b) => b - a);
console.log(ascending);
// [10, 20, 30, 40]
console.log(descending);
// [40, 30, 20, 10]
Explanation: The expression a - b sorts numbers in ascending order. The expression b - a sorts them in descending order. The spread syntax creates a copy so that the original array remains unchanged.
4. Sorting Data in React Using map() and sort()
The sort() method arranges the data, while the map() method converts each item into JSX for display.
Example: Display Products by Price
function ProductList() {
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mouse", price: 700 },
{ id: 3, name: "Keyboard", price: 1800 },
{ id: 4, name: "Monitor", price: 12000 }
];
const sortedProducts = [...products].sort(
(a, b) => a.price - b.price
);
return (
<div>
<h2>Products Sorted by Price</h2>
{sortedProducts.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
))}
</div>
);
}
export default ProductList;
Expected Output
Products Sorted by Price
Mouse - ₹700
Keyboard - ₹1800
Monitor - ₹12000
Laptop - ₹55000
The product array is copied and sorted from lowest to highest price. React then displays the sorted products using map().
5. Why Should We Copy an Array Before Sorting?
JavaScript's sort() method changes the original array. React state should be treated as read-only, so directly sorting an array stored in state can cause unwanted mutations.
Incorrect Approach
const [products, setProducts] = useState(initialProducts);
function sortProducts() {
products.sort((a, b) => a.price - b.price);
setProducts(products);
}
This approach mutates the existing state array. It also passes the same array reference back to the state setter, which may prevent React from recognizing the intended update.
Correct Approach
const [products, setProducts] = useState(initialProducts);
function sortProducts() {
const sortedProducts = [...products].sort(
(a, b) => a.price - b.price
);
setProducts(sortedProducts);
}
Explanation: The spread syntax creates a new array. Sorting the copy preserves the original array, and setProducts() updates state with the newly sorted array. React can then render the updated order.
6. Sorting Numbers in Ascending and Descending Order
Numerical sorting is commonly used for prices, marks, ages, ratings, and quantities.
Ascending Order
const marks = [85, 42, 96, 71, 60];
const ascendingMarks = [...marks].sort((a, b) => a - b);
console.log(ascendingMarks);
// [42, 60, 71, 85, 96]
Descending Order
const marks = [85, 42, 96, 71, 60];
const descendingMarks = [...marks].sort((a, b) => b - a);
console.log(descendingMarks);
// [96, 85, 71, 60, 42]
Always provide a numeric comparison function when sorting numbers. Without one, JavaScript normally sorts values by converting them to strings, which can produce unexpected numerical ordering.
7. Sorting Strings Alphabetically
String sorting is useful for names, cities, categories, course titles, and product names. The localeCompare() method compares strings according to language-sensitive sorting rules.
Ascending Alphabetical Order
const names = ["Neha", "Amit", "Rahul", "Priya"];
const ascendingNames = [...names].sort(
(a, b) => a.localeCompare(b)
);
console.log(ascendingNames);
// ["Amit", "Neha", "Priya", "Rahul"]
Descending Alphabetical Order
const descendingNames = [...names].sort(
(a, b) => b.localeCompare(a)
);
console.log(descendingNames);
// ["Rahul", "Priya", "Neha", "Amit"]
Sorting Object Names
const students = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Amit" },
{ id: 3, name: "Neha" }
];
const sortedStudents = [...students].sort(
(a, b) => a.name.localeCompare(b.name)
);
The comparison function reads each student's name property and arranges the student objects alphabetically.
8. Sorting Displayed Data with React State
React state can store the currently selected sorting option. When a user chooses a different option, the state changes and React renders the data in the new order.
Example: Sort Products Using Buttons
import { useState } from "react";
function ProductSorting() {
const [sortOrder, setSortOrder] = useState("ascending");
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mouse", price: 700 },
{ id: 3, name: "Keyboard", price: 1800 },
{ id: 4, name: "Monitor", price: 12000 }
];
const sortedProducts = [...products].sort((a, b) => {
if (sortOrder === "ascending") {
return a.price - b.price;
}
return b.price - a.price;
});
return (
<div>
<h2>Product Sorting</h2>
<button onClick={() => setSortOrder("ascending")}>
Price: Low to High
</button>
<button onClick={() => setSortOrder("descending")}>
Price: High to Low
</button>
{sortedProducts.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
))}
</div>
);
}
export default ProductSorting;
How It Works
useState() stores the selected sorting order.
- The first button sets the order to ascending.
- The second button sets the order to descending.
- The
sort() comparison function uses the selected order.
- The
map() method renders the sorted products.
- When the state changes, React re-renders the component with the new order.
9. Sorting Data with a Dropdown
A dropdown is useful when an application supports several sorting options. For example, products can be sorted by price or name.
import { useState } from "react";
function ProductSortDropdown() {
const [sortBy, setSortBy] = useState("name");
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mouse", price: 700 },
{ id: 3, name: "Keyboard", price: 1800 },
{ id: 4, name: "Monitor", price: 12000 }
];
const sortedProducts = [...products].sort((a, b) => {
if (sortBy === "priceLow") {
return a.price - b.price;
}
if (sortBy === "priceHigh") {
return b.price - a.price;
}
if (sortBy === "nameDesc") {
return b.name.localeCompare(a.name);
}
return a.name.localeCompare(b.name);
});
return (
<div>
<h2>Sort Products</h2>
<label htmlFor="sortBy">Sort by: </label>
<select
id="sortBy"
value={sortBy}
onChange={(event) => setSortBy(event.target.value)}
>
<option value="name">Name: A to Z</option>
<option value="nameDesc">Name: Z to A</option>
<option value="priceLow">Price: Low to High</option>
<option value="priceHigh">Price: High to Low</option>
</select>
{sortedProducts.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
))}
</div>
);
}
export default ProductSortDropdown;
Explanation: The dropdown stores the selected sorting option in sortBy. The comparison function checks the option and applies the appropriate sorting rule.
10. Sorting Objects by Multiple Properties
Sometimes two or more sorting criteria are required. For example, students can first be sorted by marks and then alphabetically when multiple students have the same marks.
Example: Sort Students by Marks and Name
const students = [
{ id: 1, name: "Rahul", marks: 85 },
{ id: 2, name: "Priya", marks: 92 },
{ id: 3, name: "Amit", marks: 85 },
{ id: 4, name: "Neha", marks: 76 }
];
const sortedStudents = [...students].sort((a, b) => {
if (a.marks !== b.marks) {
return b.marks - a.marks;
}
return a.name.localeCompare(b.name);
});
Explanation: The first comparison sorts marks from highest to lowest. If two students have equal marks, the second comparison sorts their names alphabetically.
11. Sorting Dates
Date sorting is useful for news articles, orders, transactions, appointments, and activity logs.
Example: Newest Records First
const orders = [
{ id: 1, name: "Order A", date: "2026-04-15" },
{ id: 2, name: "Order B", date: "2026-02-10" },
{ id: 3, name: "Order C", date: "2026-06-20" }
];
const newestFirst = [...orders].sort(
(a, b) => new Date(b.date) - new Date(a.date)
);
Oldest Records First
const oldestFirst = [...orders].sort(
(a, b) => new Date(a.date) - new Date(b.date)
);
For reliable results, use consistently formatted dates or convert values to timestamps before comparing them. Invalid date strings should be validated before sorting.
12. Combining Filtering and Sorting
Filtering and sorting are often used together. Filtering selects the records that match the user's requirements, while sorting arranges the selected records.
Example: Filter and Sort Products
const products = [
{ id: 1, name: "Laptop", category: "Electronics", price: 55000 },
{ id: 2, name: "Mouse", category: "Accessories", price: 700 },
{ id: 3, name: "Keyboard", category: "Accessories", price: 1800 },
{ id: 4, name: "Monitor", category: "Electronics", price: 12000 }
];
const results = products
.filter((product) => product.price < 20000)
.sort((a, b) => a.price - b.price);
First, products priced below ₹20,000 are selected. Then, those products are sorted from lowest to highest price. Because filter() returns a new array, sorting the filtered result does not reorder the original products array.
13. Sorting Data in a Table
Sortable tables are common in admin panels, student records, employee directories, and reports. A user can select a column to determine how the rows are ordered.
Example: Sort Students by Marks
import { useState } from "react";
function StudentTable() {
const [descending, setDescending] = useState(true);
const students = [
{ id: 1, name: "Rahul", marks: 85 },
{ id: 2, name: "Priya", marks: 92 },
{ id: 3, name: "Amit", marks: 76 },
{ id: 4, name: "Neha", marks: 88 }
];
const sortedStudents = [...students].sort((a, b) =>
descending ? b.marks - a.marks : a.marks - b.marks
);
return (
<div>
<h2>Student Marks</h2>
<button onClick={() => setDescending((value) => !value)}>
Sort {descending ? "Ascending" : "Descending"}
</button>
<table border="1" cellPadding="8" cellSpacing="0">
<thead>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
{sortedStudents.map((student) => (
<tr key={student.id}>
<td>{student.name}</td>
<td>{student.marks}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default StudentTable;
The button toggles the sorting direction. The table rows are generated from the sorted array, so the table displays the updated order.
14. Using useMemo() for Sorting Data
For large data sets or expensive sorting logic, useMemo() can cache the sorted result until its dependencies change. It is an optimization, not a requirement for every sorting operation.
import { useMemo, useState } from "react";
function EmployeeList() {
const [sortOrder, setSortOrder] = useState("ascending");
const employees = [
{ id: 1, name: "Neha", salary: 45000 },
{ id: 2, name: "Rahul", salary: 60000 },
{ id: 3, name: "Amit", salary: 35000 }
];
const sortedEmployees = useMemo(() => {
return [...employees].sort((a, b) => {
return sortOrder === "ascending"
? a.salary - b.salary
: b.salary - a.salary;
});
}, [employees, sortOrder]);
return (
<div>
<button onClick={() => setSortOrder("ascending")}>
Salary: Low to High
</button>
<button onClick={() => setSortOrder("descending")}>
Salary: High to Low
</button>
{sortedEmployees.map((employee) => (
<p key={employee.id}>
{employee.name} - ₹{employee.salary}
</p>
))}
</div>
);
}
Important: In this example, employees is a local array created during each render, so its reference changes each time. For useMemo() to provide the intended caching benefit, keep the data reference stable when appropriate, for example by storing it in state, defining static data outside the component, or receiving it from a parent that preserves the reference.
15. Sorting Data Received from an API
React applications often retrieve arrays of objects from APIs. After receiving the data, you can store it in state and sort a copied array before displaying it.
import { useEffect, useState } from "react";
function UserList() {
const [users, setUsers] = useState([]);
const [sortOrder, setSortOrder] = useState("ascending");
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function fetchUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error("Unable to load users");
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message || "Something went wrong");
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
const sortedUsers = [...users].sort((a, b) => {
return sortOrder === "ascending"
? a.name.localeCompare(b.name)
: b.name.localeCompare(a.name);
});
if (loading) return <p>Loading users...</p>;
if (error) return <p role="alert">{error}</p>;
return (
<div>
<h2>User Directory</h2>
<button onClick={() => setSortOrder("ascending")}>
Name: A to Z
</button>
<button onClick={() => setSortOrder("descending")}>
Name: Z to A
</button>
{sortedUsers.map((user) => (
<div key={user.id}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
))}
</div>
);
}
export default UserList;
How It Works
useEffect() starts the API request when the component mounts.
- The response is checked and parsed into JavaScript data.
setUsers() stores the returned user array in state.
- The sorting state determines the alphabetical direction.
[...users].sort() creates and sorts a copy of the user array.
map() renders the users in the sorted order.
- Loading and error messages handle the request's other states.
This example assumes the API returns an array of user objects. Verify the actual response structure when using a different API.
16. Sorting and Stable React Keys
When a list is reordered, React needs to identify which rendered item corresponds to each data item. A stable key helps React track the item as its position changes.
Correct Example
{sortedProducts.map((product) => (
<div key={product.id}>
{product.name} - ₹{product.price}
</div>
))}
Important Rules
- Use a stable, unique ID from the data whenever possible.
- Do not use the current sorted position as a key for a list that changes order.
- Do not generate random keys during rendering.
- Place the key on the outermost JSX element returned for each item.
For example, if products are sorted by price, the product's ID should remain its key even when its displayed position changes.
17. Common Mistakes When Sorting Displayed Data
| Mistake |
Why It Is a Problem |
Solution |
| Sorting state directly |
sort() mutates the original array. |
Copy the array first using [...items].sort(...). |
| Sorting numbers without a comparator |
Numbers may be ordered as strings rather than numerically. |
Use (a, b) => a - b or (a, b) => b - a. |
| Using the wrong object property |
The comparator may compare undefined values. |
Verify the property names and data structure. |
| Forgetting to update sorting state |
The displayed order may not change when the user interacts. |
Store the selected sorting option in React state. |
| Using array indexes as keys |
Reordering can cause items to be matched incorrectly. |
Use stable, unique item IDs. |
| Assuming all dates are valid |
Invalid dates can produce unreliable comparisons. |
Validate and normalize date values before sorting. |
| Adding useMemo() unnecessarily |
It can add complexity without meaningful performance benefits. |
Start with a straightforward copied sort and optimize only when needed. |
| Not defining a clear sorting rule |
Users may not understand the displayed order. |
Label controls clearly, such as “Price: Low to High”. |
18. Difference Between sort(), filter(), and map()
| Method |
Purpose |
Example |
sort() |
Arranges items in a specified order and mutates the array it is called on. |
[...items].sort((a, b) => a.price - b.price) |
filter() |
Selects items that satisfy a condition and returns a new array. |
items.filter(item => item.price < 5000) |
map() |
Transforms each item into a new result, often JSX. |
items.map(item => <li key={item.id}>{item.name}</li>) |
These methods can be combined to create powerful data-display features.
const displayedProducts = [...products]
.filter((product) => product.price < 20000)
.sort((a, b) => a.price - b.price);
return (
<ul>
{displayedProducts.map((product) => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
);
19. Mini Project: Student Sorting Application
Project objective: Build a student list that can be sorted alphabetically by name or numerically by marks in ascending and descending order.
Complete React Example
import { useState } from "react";
const initialStudents = [
{ id: 1, name: "Rahul Sharma", marks: 85 },
{ id: 2, name: "Priya Verma", marks: 92 },
{ id: 3, name: "Amit Kumar", marks: 76 },
{ id: 4, name: "Neha Singh", marks: 88 }
];
function StudentSortingApp() {
const [sortBy, setSortBy] = useState("nameAsc");
const sortedStudents = [...initialStudents].sort((a, b) => {
switch (sortBy) {
case "nameDesc":
return b.name.localeCompare(a.name);
case "marksAsc":
return a.marks - b.marks;
case "marksDesc":
return b.marks - a.marks;
default:
return a.name.localeCompare(b.name);
}
});
return (
<div>
<h1>Student Sorting Application</h1>
<label htmlFor="sortBy">Choose Sorting: </label>
<select
id="sortBy"
value={sortBy}
onChange={(event) => setSortBy(event.target.value)}
>
<option value="nameAsc">Name: A to Z</option>
<option value="nameDesc">Name: Z to A</option>
<option value="marksAsc">Marks: Low to High</option>
<option value="marksDesc">Marks: High to Low</option>
</select>
<table border="1" cellPadding="8" cellSpacing="0">
<thead>
<tr>
<th>Student Name</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
{sortedStudents.map((student) => (
<tr key={student.id}>
<td>{student.name}</td>
<td>{student.marks}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default StudentSortingApp;
Project Features
- Displays student records in a table.
- Sorts names from A to Z or Z to A.
- Sorts marks from lowest to highest or highest to lowest.
- Uses React state to store the selected sorting option.
- Creates a copy before sorting the data.
- Uses stable IDs as React keys.
Suggested Improvements
- Add a search field to find students by name.
- Filter students by pass or fail status.
- Add a column for course names.
- Allow sorting by course or marks.
- Load student records from an API.
- Add styling and a responsive table layout.
20. Interview Questions and Answers
Q1. What is sorting displayed data in React?
Answer: It means arranging displayed records according to a selected rule, such as alphabetical order, price, marks, rating, or date.
Q2. Which JavaScript method is used for sorting?
Answer: The sort() method arranges the elements of an array according to a comparison function.
Q3. Does sort() modify the original array?
Answer: Yes. The sort() method mutates the array on which it is called. In React, copy the array first when working with state.
Q4. How do you sort numbers in ascending order?
Answer: Use numbers.sort((a, b) => a - b). When preserving the original array, use [...numbers].sort((a, b) => a - b).
Q5. How do you sort numbers in descending order?
Answer: Use a comparison function such as (a, b) => b - a.
Q6. How do you sort strings alphabetically?
Answer: Use localeCompare(), for example a.name.localeCompare(b.name).
Q7. Why is React state important for sorting?
Answer: State can store the selected sorting option. Updating it triggers a re-render so the displayed list reflects the new order.
Q8. Can sorting be combined with filtering?
Answer: Yes. Filter the data to select matching records, sort the resulting array, and then use map() to render it.
Q9. Why are stable keys important when sorting a list?
Answer: Stable keys help React identify each item when its position changes, reducing the risk of incorrect item matching during updates.
Q10. When should useMemo() be used for sorting?
Answer: Use useMemo() when sorting is sufficiently expensive and caching the result is useful. Simple sorting usually does not require it.
Q11. How can you sort objects by a date property?
Answer: Convert valid date values into timestamps and compare them numerically, taking care to validate the input data.
Q12. How do you let users choose the sorting order?
Answer: Store the selected option in state and provide controls such as buttons or a dropdown. Use that state in the comparison function.
21. Practice Exercises
- Create an array of products and sort them by price from low to high.
- Sort the same products from high to low.
- Create a list of employee names and sort them alphabetically.
- Sort student objects by marks in descending order.
- Build a dropdown that sorts products by name or price.
- Create a sortable table with student names and marks.
- Sort orders by date, showing the newest order first.
- Filter products by category and then sort them by price.
- Build a student sorting application with four sorting options.
- Retrieve data from an API and add alphabetical sorting.
- Use stable keys to render a list that changes its order.
- Experiment with sorting a copied array versus sorting an array directly.
22. Best Practices for Sorting in React
- Copy an array before calling
sort() when the original data must remain unchanged.
- Use a comparison function for numerical sorting.
- Use
localeCompare() for string comparisons when appropriate.
- Keep sorting controls clear and accessible.
- Store interactive sorting choices in React state.
- Use stable and unique keys when rendering sorted lists.
- Validate dates and numerical values before comparing them.
- Combine sorting with filtering when users need both features.
- Use
useMemo() only when caching provides a useful performance benefit.
- For very large data sets, consider server-side sorting and pagination.
23. Quick Revision Checklist
- Understand the purpose of sorting displayed data.
- Know how the JavaScript
sort() method works.
- Sort numbers in ascending and descending order.
- Sort strings using
localeCompare().
- Sort arrays of objects by a property.
- Copy arrays before sorting React state data.
- Use React state to control sorting options.
- Implement buttons and dropdowns for sorting.
- Sort by multiple properties and dates.
- Combine sorting with filtering and list rendering.
- Use stable keys and follow React state best practices.
24. Conclusion
Sorting displayed data is an essential React JS skill for building organized and interactive applications. JavaScript's sort() method arranges data, React state allows users to select a sorting order, and map() renders the sorted records. By combining sorting with filtering, tables, dropdowns, and API data, you can create practical features for product catalogs, student management systems, employee directories, and dashboards.
Practise the examples and mini project to understand how sorting works with arrays, objects, React state, and dynamic rendering.
25. React JS Training and Course Demo
Explore the following resources to learn more about React JS, rendering lists, sorting data, and updating arrays in state.