cresjoy cresjoy - 1 year ago 67
JSON Question

Getting JSON values by order and keeping the corresponding names in order

I currently have some JSON data like the following:

{"data": [
{"student_id": "bobby", "solved": 19},
{"student_id": "smith", "solved": 20}

Now what I am doing right now is pushing the solved values into an array called
in a for loop like the following:


Now I sort these by values by using this function:

return a-b;

Great, now I have an array of values in order. But how can I retrieve the names which correspond to these values which I sorted in order? It would be nice if I could have the names and solved in two arrays, but each index corresponds to the same in the original JSON data. One huge array with objects and values sorted is ok too I guess.

Answer Source

You can first sort data by solved key and then use map() to return two separate arrays of results in sorted order.

var obj = {"data": [{"student_id": "bobby", "solved": 19}, {"student_id": "smith", "solved": 20}]}

var newData =, b) {
  return b.solved - a.solved;

var numbers = => e.solved);
var names = => e.student_id);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download