javascriptbotkit

Sort json table by time


. Hello,

I have this json file :

{
  "fbl": {
    "id": "fbl",
    "user_id": "fbl@xxx.fr",
    "nb_error": 0,
    "time": "1:27.700"
  },
  "dev": {
    "id": "dev",
    "user_id": "dev@xxx.fr",
    "nb_error": 0,
    "time": "1:12.54"
  },
  "jul": {
    "id": "jul",
    "user_id": "jul@xx.fr",
    "nb_error": 0,
    "time": "0:58.700"
  }
}

I want read this file and sort it in the order of the shortest time to the longest time (do not modify the file, just retrieve the values sort to display them with botkit).

First, for read this file I use :

fs.readFileSync('course.json/quiz.json', 'utf8');

It's a good choice ?

And can you help me to sort these values for to then display them?

Thank you


Solution

  • if you want to change the order just flip the values in the comparator function

    let data = {
      "fbl": {
        "id": "fbl",
        "user_id": "fbl@xxx.fr",
        "nb_error": 0,
        "time": "1:27.700"
      },
      "dev": {
        "id": "dev",
        "user_id": "dev@xxx.fr",
        "nb_error": 0,
        "time": "1:12.54"
      },
      "jul": {
        "id": "jul",
        "user_id": "fbl@xx.fr",
        "nb_error": 0,
        "time": "0:58.700"
      }
    }
    
    const formatTime =(time)=> parseFloat(time.replace(":",""))
    
    const compareTime = (a,b)=>{
      let a_time = formatTime(a["time"])
      let b_time = formatTime(b["time"])
      return a_time-b_time
    }
    
    const sort = (data) => {
    let keys = Object.keys(data)
    let dataAsArray = keys.map(e=>data[e])
    return dataAsArray.sort(compareTime)
    }
    console.log(sort(data))