How to sort an array of objects in ascending and descending order of React app
- Admin
- Dec 31, 2023
- Typescript Reactjs
In this tutorial, You learned how to sort an array of objects by ascending and descending order in React component render component. We have an array of object data either coming from API or fixed.
For example,
employeeList = [
{
name: "John",
email: "[email protected]",
},
{
name: "Ram",
email: "[email protected]",
},
{
name: "Abc",
email: "[email protected]",
},
];
Javascript array has a sort
function that sorts a default order.
Let’s see how to iterate using the Array. map method to in react component.
React class component to Sort ascending and descending
- Created a react component
app.jsx
- we have an array of objects stored in react state object
- Created two button elements for
ascending
anddescending
- Created binding functions for ascending and descending
Here is a code for sorting an array of objects in ascending order
sortByAscending() {
let sortedAsceding = this.state.data.sort((a, b) => {
return a.name - b.name;
});
this.setState({
data: sortedAsceding
});
}
Here is a code for sorting an array of objects in descending order
sortByDescending() {
let sortedDescending = this.state.data.sort((a, b) => {
return b.name - a.name;
});
this.setState({
data: sortedDescending
});
}
In the
render
method, Iterated array of objects using themap
method and construct the result objectIn the render method add this result using the javascript expression syntax
import React from "react";
import "./style.css";
import React, { Component } from "react";
import { render } from "react-dom";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{
name: "John",
email: "[email protected]",
},
{
name: "Ram",
email: "[email protected]",
},
{
name: "Abc",
email: "[email protected]",
},
],
};
this.sortByAscending = this.sortByAscending.bind(this);
this.sortByDescending = this.sortByDescending.bind(this);
}
sortByAscending() {
let sortedAsceding = this.state.data.sort((a, b) => {
return a.name - b.name;
});
this.setState({
data: sortedAsceding,
});
}
sortByDescending() {
let sortedDescending = this.state.data.sort((a, b) => {
return b.name - a.name;
});
this.setState({
data: sortedDescending,
});
}
render() {
const emps = this.state.data;
const result = emps.map((emp, index) => <li key={index}>{emp.name}</li>);
return (
<div>
<button onClick={this.sortByAscending}>ASC</button>
<button onClick={this.sortByDescending}>DESC</button>
<ul>{result}</ul>
</div>
);
}
}
Whenever an ascending button is clicked, Names are printed in ascending order and descending names are displayed on clicking the descending button.
Conclusion
In this tutorial, You learned how to sort a field in an array of objects by ascending and descending order in react components.