I have a Record : Record<string, Formulaire>
that is displayed as a list using
Object.keys(obj).map((id) => (
<li> {obj[id].content} - {obj[id].date} </li>
))
But I want this to be displayed ordered by date.
I was expecting the method sort to work on Record and using it like this :
obj.sort((a,b) => ((a.date > b.date) ? 1 : -1))
but object don’t have sort
method, so what is the best way of sorting this array before displaying it ?
2
Answers
As stated in the comments, the sort method is part of the Array prototype and does not exist on Object of which the
Record
type is the most common typing of. Therefore you need to do a similar thing you did to usemap
(which is also an Array method) and create an array form an object using eitherObject.keys
,Object.values
orObject.entries
.Doing minimal changes to the code you’ve shared you can do the following:
You can create an array of the dates and sort it using whatever your formula is and then combine it with the object again with this code.