Can anyone help me with the sorting of json data in ReactJs please? Right now it is not working properly for me. Also if i want to sort as per the title, would it be same? Thanks.
I am trying as below:
componentDidMount()
{
fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
.then((data) => {
data.sort(function (a, b) {
return a.userId> b.userId;
})
data.sort();
this.setState({data: data});
});
}
render() {
return (
<div>
<br/><br/>
<br/><br/>
< table className="table">
<th>User Id</th>
<th>Name</th>
<th>Address</th>
<th>Action</th>
<tbody>{this.state.data.map(function (item, key) {
return (
<tr key={key}>
<td>{item.userId}</td>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.body}</td>
</tr>
)
})}</tbody>
</table>
</div>
)
}
data.sort()(without custom sort function logic) is overwriting the initial sort logic which is why your custom logic of comparinga.userID > b.userIdis not achieving any expected results. @gaiazov Answer belowa.title - b.titleanswers the sort-by-title question.