I am trying to display the list of items that i am getting response from my get
request response. So How do I sort on the basis of created date Mon, 18 Oct 2021 22:46:50 GMT
is the date format I am displaying to my table.
My code goes:
const display = todoList
.sort((a, b) => {
return (
new Date(a.createdAt).toUTCString() -
new Date(b.createdAt).toUTCString()
);
})
.map((item) => (
<tr key={item.id}>
<td>{item.title}</td>
<td>{new Date(item.CreatedAt).toUTCString()}</td>
<td>
<button onClick={() => Update(item.id)} className="btn btn-success">
Update
</button>
</td>
<td>
<button onClick={() => remove(item.id)} className="btn btn-Danger">
Delete
</button>
</td>
</tr>
));
CodePudding user response:
Please take a look at the MDN Webdocs for sort()
. Specifically, look at their example, it is returning 0
, -1
, or 1
, and only these values. Your function, on the other hand, returns a UTC date (minus) another UTC date. What you need is not "string1 - string2"
, but "if string1 > string2 return 1, else"
, etc...
Change your sort to use -1
or 1
, and string >
comparisons instead of string -
comparisons, like below, and it'll sort correctly...
todoList = [
{'createdAt':'2000-01-01 12:00:00'},
{'createdAt':'2000-01-01 10:00:00'},
];
todoList.sort((a, b) => {
if(new Date(a.createdAt) > new Date(b.createdAt)) {
return 1;
}
return -1;
});
console.log(todoList);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Your sort will not work like that. You can try something like this. I have no clue how your toDoList array looks, but here's a guess. And then you map.
toDoList.sort((a,b)=> {
return new Date(b.createdAt) - new Date(a.createdAt);
});