I'm new to using Javascript and trying to sort the objects.
What i have is objects Player in array playerLst. Every Player has property name, score, coeficent and ratio and of course the place (from non-english speaking country, there's probably a better word for this, with place i describe his positsion in table, for example, first, second third or so).
So i would like to sort the players using their score, coeficent and ratio and depending on that they will get their place.
I think the easyest way is to do a little playthrough example:
Player1.name = A;
Player1.score = 5;
Player1.coeficent = 4;
Player1.ratio = "22:8";
Player2.name = B;
Player2.score = 5;
Player2.coeficent = 6;
Player2.ratio = "24:8";
Player3.name = C;
Player3.score = 6;
Player3.coeficent = 2;
Player3.ratio = "1:0";
Player4.name = D;
Player4.score = 4;
Player4.coeficent = 3;
Player4.ratio: "10:5";
Player5.name = E;
Player5.score = 4;
Player5.coeficent = 3;
Player5.ratio: "8:5";
playerLst = [Player1, Player2, Player3, Player4, Player5];
So currently as we can see that obvious winner is Player3 because he has the maximum amount of points. So Player3.place should be after sort = 1. Player 1 & Player 2 have equal score which means their coeficents will be measured. Player2 has higher coeficent so he gets .place = 2 and player 1 gets .place = 3. Now we still have two players, D & E, who have same score and coeficent so ratios will be measured. Player D has better ratio than E so player D gets .place = 4 and player E .place = 5.
I've dealt with this issue several hours now and my brain is melting, i have tried to do it with different for cycles but still ended up in some error. If someone could provide something useful i'd appreciate it. Thanks!
E2: Added jsfiddle how the comparing should look like http://jsfiddle.net/4ep7k7yf/
E3:
This is my function for comparing:
function suuremKuiTeine(player1,player2){
if (player1.punkte > player2.punkte){
return 1;
}
else if (player2.punkte > player1.punkte){
return -1;
}
else{ //scores are equal
if (player1.koef > player2.koef){
return 1;
}
else if (player2.koef > player1.koef){
return -1;
}
else{ //coeficents are equal
ratio1 = player1.suhe;
ratio_split = ratio1.split(":");
ratio1 = parseInt(ratio_split[0])-parseInt(ratio_split[1]);
ratio2 = player2.suhe;
ratio_split = ratio2.split(":");
ratio2 = parseInt(ratio_split[0])-parseInt(ratio_split[1]);
if (ratio1 > ratio2){
return 1;
}
else if (ratio2 > ratio1){
return -1;
}
else{
return 0;
}
}
}
}
With some alert magic i found that the ratios, score and coeficent are calculated correctly. However after the endless stream of alerts end
playerLst = playerLst.sort(suuremKuiTeine); //is global variable!
for (var i = 0; i<playerLst.length;i++){
alert(playerLst[i].name);
}
The values are still the same. What am i doing wrong?