James Oshomah James Oshomah - 1 year ago 69
Javascript Question

Sorting An Array Inside An Array Of Objects

Hello I have an array of this form which I am displaying on my meteor template.

var data = [{text_name:'My life',
score: [{name : 'james',score: 10},
{name : 'john',score : 40},
{name : 'Abu',score : 80}]},
{text_name:'The game real',
score: [{name : 'penny',score: 30}
{name : 'john',score : 20} ,
{name : 'Abu',score : 30}] }]

I want to sort the
key which is an array of objects in descending order. Using the example data in the
text_name:'My life'
I want Abu scores to display first because he scored highest.

I have tried sorting by using the code found on this link Sorting an array of JavaScript objects.

Answer Source

If I understand correctly, what you're trying to do is have each list sorted within itself.

So here's what you'd need to do:

// iterate over data
for (var i = 0; i < data.length; i++) {
  var item = data[i];
  // sort the item's score
  item.score.sort(function(a, b) {
    return b.score - a.score;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download