0

Possible Duplicate:
How to sort an array of javascript objects?

I have a array myResponse.students[i]

I calculate the Total marks for every student in the array through some logic and now i want to sort the array based on total marks which i calculate. How to do this using javascript?

Community
  • 1
  • 1
coderslay
  • 13,960
  • 31
  • 73
  • 121
  • Is this an array of numbers or an array of objects? – Felix Kling Sep 28 '12 at 06:00
  • possible duplicate of [How to sort an array of javascript objects?](http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects) and [Sort JavaScript array of Objects](http://stackoverflow.com/questions/5421253/sort-javascript-array-of-objects). – Felix Kling Sep 28 '12 at 06:00
  • @FelixKling Its array of Objects... To get the name i need to do this `myResponse.students[i].student.name` – coderslay Sep 28 '12 at 06:07

3 Answers3

3

assume as your students is the array you want to sort

myResponse.students.sort(byMark)

function byMark(a, b){
     return b.mark - a.mark; // sort score desc
}
hsgu
  • 834
  • 4
  • 9
  • 18
  • sort function will pick and object in array as a and b to compare. you can do anything in sort function to return your defind value. return value will tell compare function how to sort. return 0 = equal, return 1 or greater mean a is greater , return -1 or lower mean a is lower than b – hsgu Sep 28 '12 at 06:36
  • Hi... I understood it. But in my case the Total marks are not in array... I calculate it outside... – coderslay Sep 28 '12 at 06:50
  • can you show your total marks calculate function? may be you want this `function byMark(a,b){ return cal(a) - cal(b); }` if your calculate function calculate from your array object – hsgu Sep 28 '12 at 07:09
0

Try this

myResponse.students.sort(function(a,b) { 
    return parseFloat(a.TotalMarks) - parseFloat(b.TotalMarks) ;
});

The signature of sort function is this

array.sort([compareFunction])

Please go through the documentation to get a better idea of compareFunction

Link: array.sort MDN

naveen
  • 53,448
  • 46
  • 161
  • 251
0

See MDN

You can pass your comparator function as parameter to the sort function.

This function takes two values to be compared from the array, and you need to provide logic for returning 0 or 1 or -1 as following

var a = [...]; //your array
a.sort(compareFunction);

function compareFunction (a, b)
{
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
}
prashanth
  • 2,059
  • 12
  • 13