-1

. 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

nobody
  • 19,814
  • 17
  • 56
  • 77
SkroS
  • 9
  • 5
  • 1
    You can safely extract these values into array with Object.values and then sort the resulting array using time. The time string can be parsed many various ways, using some custom function or Moment.js for example – lucifer63 Dec 11 '18 at 14:11
  • Hi! Welcome to StackOverflow. [This](https://stackoverflow.com/help/mcve) and [this](https://stackoverflow.com/help/how-to-ask) are some good resources for how to create the best question possible. Also, [here](https://www.w3schools.com/jsref/jsref_sort.asp) is a link to the javascript `sort` method. You can make your own custom method that compares the time strings. – TheCrzyMan Dec 11 '18 at 14:14

1 Answers1

0

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))
Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48