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?

3

3 Answers 3

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 } 
Sign up to request clarification or add additional context in comments.

3 Comments

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
Hi... I understood it. But in my case the Total marks are not in array... I calculate it outside...
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
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; } 

Comments

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

1 Comment

Hi Naveen.. What is a & b here?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.