Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Felix Kling, pad, skolima, Jason Sturges, Ja͢ck Sep 28 '12 at 14:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Is this an array of numbers or an array of objects? –  Felix Kling Sep 28 '12 at 6:00
    
    
@FelixKling Its array of Objects... To get the name i need to do this myResponse.students[i].student.name –  Coder_sLaY Sep 28 '12 at 6:07

3 Answers 3

up vote 2 down vote accepted

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
}
share|improve this answer
    
What is a & b here? –  Coder_sLaY Sep 28 '12 at 6:12
    
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 6:36
    
Hi... I understood it. But in my case the Total marks are not in array... I calculate it outside... –  Coder_sLaY Sep 28 '12 at 6: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 7:09
    
Ok got it... Thanks :) –  Coder_sLaY Sep 28 '12 at 8:28

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;
}
share|improve this answer

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

share|improve this answer
    
Hi Naveen.. What is a & b here? –  Coder_sLaY Sep 28 '12 at 6:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.