lundi 29 juillet 2019

Checking loop for match most efficiently

I have a simple set up to find top scores. The goal is to order who received the highest scores and then give the top 3 bonus points.

Question: In part two below I am looping through the people and checking who got the top score. The issue is I need to do this 3 times for each name. The way I currently have the loop set up works but seems very redundant. Is this the correct way to do it?

   var allGrades = [
        {name: 'andrew', score: 80}, 
        {name: 'john', score: 90}, 
        {name: 'sam', score: 31}, 
        {name: 'frank', score: 50}, 
        {name: 'dave', score: 95},
        ]

    allGrades.sort(function(obj1, obj2) {
    return obj2.score - obj1.score;
     });

Part two. Giving the top 3 scoring people a bonus of 50/25/15 accordingly.

for (i = 1; i < 5; i++) {

if (allGrades[0].name == 'andrew'){
andrewGradeBonus = 50; 
if (allGrades[1].name == 'andrew'){
andrewGradeBonus = 25;
if (allGrades[2].name == 'andrew'){
andrewGradeBonus = 15;

if (allGrades[0].name == 'dave'){
daveGradeBonus = 50; 
if (allGrades[1].name == 'dave'){
daveGradeBonus = 25;
if (allGrades[2].name == 'dave'){
daveGradeBonus = 15;

continued for all names...

Aucun commentaire:

Enregistrer un commentaire