colleen colleen - 4 months ago 22
Javascript Question

How to show a value from array that relates to the value of another array, javascript

I am trying to have the name show up with the score that relates to that name. So if the highest score is 98 I want Joels name to show up in the display where is says name here.

var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var average;
var total = 0;
var highestScore = 0;

var $ = function (id) { return document.getElementById(id); };

var displayResults = function () {
for (var i = 0; i < scores.length; i++) {
total = total + scores[i]; //both are numbers so adds
if (scores[i] > highestScore) {
highestScore = scores[i];
}

}

//then calculate the average and display
average = parseInt(total/scores.length);
document.getElementById("results_header").innerHTML =
("Results");
document.getElementById("results").innerHTML = ("\nAverage score
is " + average + "\nHigh score = Name here with a score of " +
highestScore);


};

window.onload = function () {
//$("add").onclick = addScore;
$("display_results").onclick = displayResults;
//$("display_scores").onclick = displayScores;
};

Answer

Try it :

<html>
    <head>
        <style>
        </style>
    </head>
    <body>
        <p id="results"></p>
        <button id="display_results">Show</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
               var names = ["Ben", "Joel", "Judy", "Anne"];
                var scores = [88, 98, 77, 88];
                var average;
                var total = 0;
                var highestScore = 0;
                var hightName = "";
                function displayResults () {
                    for (var i = 0; i < scores.length; i++) {
                            total = total + scores[i];       //both are numbers so adds
                                if (scores[i] > highestScore) {
                                    highestScore = scores[i];
                                    hightName = names[i];
                                }
                    }

                //then calculate the average and display
                        average = parseInt(total/scores.length);
                        document.getElementById("results").innerHTML = ("\nAverage score is " + average + "\n High score = " + hightName + " with a score of " +  highestScore);

                };
            
                    //$("add").onclick = addScore;
                   $(document).ready(function(){
                       $("#display_results").click(function(){
                           displayResults();
                       })
                       
                   })

        </script>
    </body>
</html>

Comments