skip to Main Content

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


  1. 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>))
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search