-1

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 score 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.

Community
  • 1
  • 1
James Oshomah
  • 224
  • 2
  • 12
  • 1
    That's not valid JavaScript. Please fix so we know what you mean (is it `score:[...`?) Also, if you have tried, post what went wrong. *Also*, why is this tagged [tag:meteor]? – Amadan May 10 '16 at 01:18
  • That's not valid JavaScript. A comma is missing after the first `score: 30}`. – Pang May 10 '16 at 03:11

2 Answers2

1

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;
  });
}
smaili
  • 1,245
  • 9
  • 18
0

Try using the sort method:

Also note, that as the comments have mentioned that is not valid JS, I added the correct format in the example posted above.

Working example

var d = data.map(function(d) {
  return d.score.sort(function(a, b) {
    return a.score + b.score;
  });
});
omarjmh
  • 13,632
  • 6
  • 34
  • 42