Introduction
Sorting Data is a common requirement in React applications when users need to arrange information by name, price, date, rating, or other values. JavaScript provides the sort() method for sorting arrays, but care is needed because sort() changes the original array. In React, state should be updated without directly mutating it. In this chapter, we will solve practical questions on sorting numbers, strings, objects, and dynamic data. React js Sorting Data Practice Questions with ssolutions help to understand the concepts.
1. How do you sort numbers in React?
JavaScript’s sort() method can sort numbers using a comparison function.
function App() {
const numbers = [50, 10, 40, 20, 30];
const sortedNumbers = [...numbers].sort((a, b) => a - b);
return (
<div>
{sortedNumbers.map((number) => (
<p key={number}>{number}</p>
))}
</div>
);
}
export default App;
a - b sorts the numbers in ascending order.
2. How do you sort numbers in descending order?
Use b - a in the comparison function.
function App() {
const numbers = [50, 10, 40, 20, 30];
const sortedNumbers = [...numbers].sort((a, b) => b - a);
return (
<div>
{sortedNumbers.map((number) => (
<p key={number}>{number}</p>
))}
</div>
);
}
export default App;
Output:
50
40
30
20
10
3. How do you sort an array of names alphabetically?
For strings, you can use localeCompare().
function App() {
const names = ["Rahul", "Amit", "Priya", "Neha"];
const sortedNames = [...names].sort((a, b) =>
a.localeCompare(b)
);
return (
<div>
{sortedNames.map((name) => (
<p key={name}>{name}</p>
))}
</div>
);
}
export default App;
The spread operator creates a copy before sorting.
4. How do you sort products by price?
When working with objects, access the property you want to sort.
function App() {
const products = [
{ id: 1, name: "Laptop", price: 60000 },
{ id: 2, name: "Mouse", price: 800 },
{ id: 3, name: "Keyboard", price: 1500 }
];
const sortedProducts = [...products].sort(
(a, b) => a.price - b.price
);
return (
<div>
{sortedProducts.map((product) => (
<p key={product.id}>
{product.name} - ₹{product.price}
</p>
))}
</div>
);
}
export default App;
This displays the cheapest product first.
5. How do you sort products from highest price to lowest price?
Change the comparison function to b.price - a.price.
const sortedProducts = [...products].sort(
(a, b) => b.price - a.price
);
Complete example:
function App() {
const products = [
{ id: 1, name: "Laptop", price: 60000 },
{ id: 2, name: "Mouse", price: 800 },
{ id: 3, name: "Keyboard", price: 1500 }
];
const sortedProducts = [...products].sort(
(a, b) => b.price - a.price
);
return (
<div>
{sortedProducts.map((product) => (
<p key={product.id}>
{product.name} - ₹{product.price}
</p>
))}
</div>
);
}
export default App;
6. How do you create a sorting option using React state?
You can store the selected sorting option in state.
import { useState } from "react";
function App() {
const [sortOrder, setSortOrder] = useState("asc");
const numbers = [50, 10, 40, 20, 30];
const sortedNumbers = [...numbers].sort((a, b) => {
return sortOrder === "asc" ? a - b : b - a;
});
return (
<div>
<button onClick={() => setSortOrder("asc")}>
Low to High
</button>
<button onClick={() => setSortOrder("desc")}>
High to Low
</button>
{sortedNumbers.map((number) => (
<p key={number}>{number}</p>
))}
</div>
);
}
export default App;
When sortOrder changes, React renders the list again with the selected order.
7. How do you sort users by name?
You can sort an array of user objects using localeCompare().
function App() {
const users = [
{ id: 1, name: "Ravi" },
{ id: 2, name: "Amit" },
{ id: 3, name: "Neha" }
];
const sortedUsers = [...users].sort((a, b) =>
a.name.localeCompare(b.name)
);
return (
<div>
{sortedUsers.map((user) => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
}
export default App;
This sorts the users alphabetically by their name.
8. How do you sort data by rating?
You can use a numeric property such as rating.
function App() {
const products = [
{ id: 1, name: "Laptop", rating: 4.2 },
{ id: 2, name: "Phone", rating: 4.8 },
{ id: 3, name: "Tablet", rating: 4.5 }
];
const sortedProducts = [...products].sort(
(a, b) => b.rating - a.rating
);
return (
<div>
{sortedProducts.map((product) => (
<p key={product.id}>
{product.name} - ⭐ {product.rating}
</p>
))}
</div>
);
}
export default App;
Here, products with higher ratings appear first.
9. Why should you avoid directly using sort() on a state array?
sort() mutates the array it is called on. If that array is stored in React state, directly sorting it can mutate the existing state.
Avoid:
const [numbers, setNumbers] = useState([50, 10, 30]);
numbers.sort((a, b) => a - b);
Instead, create a copy:
const sortedNumbers = [...numbers].sort((a, b) => a - b);
If you need to store the sorted array as state, update it with a new array:
setNumbers((currentNumbers) =>
[...currentNumbers].sort((a, b) => a - b)
);
The important idea is to avoid mutating the existing state array directly.
10. How do you create a practical product sorting application in React?
You can combine React state with sort() to allow users to sort products by price or name.
import { useState } from "react";
function App() {
const [sortBy, setSortBy] = useState("price");
const products = [
{ id: 1, name: "Laptop", price: 60000 },
{ id: 2, name: "Mouse", price: 800 },
{ id: 3, name: "Keyboard", price: 1500 },
{ id: 4, name: "Monitor", price: 12000 }
];
const sortedProducts = [...products].sort((a, b) => {
if (sortBy === "price") {
return a.price - b.price;
}
if (sortBy === "name") {
return a.name.localeCompare(b.name);
}
return 0;
});
return (
<div>
<h2>Product List</h2>
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
>
<option value="price">Sort by Price</option>
<option value="name">Sort by Name</option>
</select>
{sortedProducts.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
))}
</div>
);
}
export default App;
This example demonstrates a practical sorting system where the user can select how the product list should be arranged.
Key Takeaways
- JavaScript’s
sort()method is commonly used for sorting data in React. - Use
(a, b) => a - bfor ascending numbers. - Use
(a, b) => b - afor descending numbers. - Use
localeCompare()for string-based sorting. - For object arrays, compare the required property such as
price,name, orrating. sort()mutates the array, so avoid directly sorting a state array.- Use
[...array].sort()when you need a sorted copy. - Sorting can be controlled using React state.
- Stable unique IDs should be used as keys when rendering sorted lists.
- For large datasets, server-side sorting may be more suitable than sorting a very large array in the browser.
FAQs
1. What is sorting in React?
Sorting in React means arranging data in a particular order, such as ascending price, descending price, alphabetical name, or highest rating.
2. Which JavaScript method is used for sorting data?
The JavaScript sort() method is commonly used to sort arrays.
3. How do you sort numbers in ascending order?
Use:
numbers.sort((a, b) => a - b);
When the array is state, prefer sorting a copy:
[...numbers].sort((a, b) => a - b);
4. How do you sort strings alphabetically?
You can use localeCompare():
names.sort((a, b) => a.localeCompare(b));
For React state, use a copied array before sorting.
5. Why is [...array].sort() used in React?
Because sort() changes the array in place. [...array] creates a new array first, allowing the sorting operation to avoid mutating the original array.
6. Can sorting be controlled using React state?
Yes. You can store the selected sorting option in state and calculate the sorted list based on that option.
const [sortOrder, setSortOrder] = useState("asc");
7. Can sorting and filtering be used together in React?
Yes. You can first filter the data and then sort the resulting array.
const result = products
.filter((product) => product.price > 1000)
.sort((a, b) => a.price - b.price);
This can be useful for product lists, search applications, dashboards, and e-commerce interfaces.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
