Correlation in Javascript lists

Asked

Viewed 43 times

0

I would like to associate the Scores[] list with the costs[] list to get the highest value from the first and the lowest value from the second. However the function getMostEffective() returns the index #Undefined, why?:

var scores=[60,50,60,58,54,58,50,69,34,55,69,54];
var costs=[25,27,34,30,25,24,26,27,28,29,30,22];

function printAndGetHighScore(scores){
    var highScore=0;
    var output;
    for (var i=0;i<scores.length;i++){
        output="Bubble solution #"+i+" score: "+scores[i];
        console.log(output);
        if(scores[i]>highScore){
            highScore=scores[i];
        }
    }
    return highScore;
}

function getBestsResults(scores,highScore){
    var bestSolutions=[];
    for (var i=0;i<scores.length;i++){
        if(scores[i]==highScore){
            bestSolutions.push(i);
        }
    }
    return bestSolutions;
}

function getMostEffective(scores,costs,highScore){
    var cost=100;
    var index;
    for(var i=0;i<scores.legth;i++){
        if (scores[i]==highScore){
            if (cost>costs[i]){
                index = i;
                cost = costs[i];
            }
        }
    }
return index;
}

var highScore=printAndGetHighScore(scores);
console.log("Bubbles tests: "+scores.length);
console.log("Highest bubble score: "+highScore);

var bestSolutions=getBestsResults(scores,highScore);
console.log("Solutions with the highest score: "+bestSolutions);

var mostEffective=getMostEffective(scores,costs,highScore);
console.log("Bubble Solution #"+mostEffective+" is the best!");

2 answers

0

You put legth instead of length, with the code below will work:

function getMostEffective(scores,costs,highScore){
    var cost=100;
    var index;
    for(var i=0;i<scores.length;i++){
        if (scores[i]==highScore){
            if (cost>costs[i]){
                index = i;
                cost = costs[i];
            }
        }
    }
return index;
}

0


There is a typo in your getMostEffective function, when you loop the array, it is legth instead of length . Make the following change:

function getMostEffective(scores,costs,highScore){
    var cost=100;
    var index;
    for(var i=0;i<scores.length;i++){
        if (scores[i]==highScore){
            if (cost>costs[i]){
                index = i;
                cost = costs[i];
            }
        }
    }
return index;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.