0

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 ?

I saw this question : Sort JavaScript object by key but my problem is different as I'm working with a typescript Record and I want it to be displayed by on the propertie associated with each key and not by the key itself.

A solution given bellow is actually ordering the list of keys using a property of the object associated with that key.

AntoninL
  • 154
  • 7

2 Answers2

3

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 use map (which is also an Array method) and create an array form an object using either Object.keys, Object.values or Object.entries.

Doing minimal changes to the code you've shared you can do the following:

  Object.keys(obj)
    .sort((idA, idB) => ((obj[idA].date > (obj[idB].date) ? 1 : -1))
    .map((id) => (<li> {obj[id].content} - {obj[id].date} </li>))
5ar
  • 2,069
  • 10
  • 27
  • 1
    thanks, I don't know why I was trying to sort my object before passing it to the `Object.keys()` method but this is excactly what I wanted to do – AntoninL Aug 29 '23 at 14:18
0

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.

let cars = [
  { name: "car1", speed: 30 },
  { name: "car2", speed: 20 },
  { name: "car3", speed: 40 },
  { name: "car4", speed: 10 },
];

let speeds = cars.map(car => car.speed)
let sortedSpeeds = [...speeds].sort((a,b) => a - b)

let newObj = sortedSpeeds.map(speed => {
  return {
    name: cars[speeds.indexOf(speed)].name,
    speed: speed,
  }
})

console.log(newObj)
Jesse
  • 334
  • 15