cresjoy cresjoy - 4 months ago 7
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
newData
in a for loop like the following:

newData.push(data['data'][i].solved);


Now I sort these by values by using this function:

newData.sort(function(a,b){
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

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 = obj.data.sort(function(a, b) {
  return b.solved - a.solved;
});

var numbers = newData.map(e => e.solved);
var names =  newData.map(e => e.student_id);

console.log(numbers);
console.log(names);