ReactJs Sort an array of objects by the length of a nested array
ReactJs Sort an array of objects by the length of a nested array:To sort an array of objects in ReactJS by the length of a nested array, you can use the Array.prototype.sort()
method with a custom comparator function. First, extract the nested array's length from each object. Then, compare these lengths in the comparator function and return the appropriate value for sorting




Thanks for your feedback!
Your contributions will help us to improve service.
How to sort an array of objects in ReactJS by the length of a nested array?
This ReactJS code defines a component called "App" that manages an array of objects, each containing an "id" and a nested array called "schools." The code provides a button that, when clicked, sorts the array of objects based on the length of the "schools" array in each object. It uses the useState
hook to manage the state of the data and updates it with the sorted result. The sorted data is then displayed in an unordered list. When the "Sort by School Length" button is clicked, it triggers the sorting function, reordering the objects by the length of their nested "schools" arrays.
ReactJs Sort an array of objects by the length of a nested array
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [schoolData, setSchoolData] = useState([
{ id: 1, schools: ["Harvard University", "Stanford University"] },
{ id: 2, schools: ["Massachusetts Institute of Technology"] },
{ id: 3, schools: ["University of California, Berkeley", "University of Texas at Austin"] },
{ id: 5, schools: ["California Institute of Technology", "Columbia University"] },
{ id: 7, schools: ["Cornell University", "University of Pennsylvania,University of Chicago", "Princeton University", "Yale University"] },
{ id: 8, schools: ["Duke University", "Northwestern University"] },
{ id: 9, schools: ["University of Michigan, Ann Arbor"] },
{ id: 10, schools: ["University of California, Los Angeles", "University of Florida"] },
// Add more objects with nested arrays of schools here
]);
const sortSchoolsByLength = () => {
const sortedSchoolData = [...schoolData].sort(
(a, b) => a.schools.length - b.schools.length
);
setSchoolData(sortedSchoolData);
};
return (
<div className='container'>
<h3>ReactJs Sort An Array Of Objects By The Length Of A Nested Array</h3>
<button className='sort-button' onClick={sortSchoolsByLength}>Sort by School Length</button>
<ul className='school-list'>
{schoolData.map((item) => (
<li key={item.id} className='school-item'>{item.id} {item.schools.join(', ')}</li>
))}
</ul>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>