Avatar of Steve Tinsley
Steve Tinsley
Flag for United Kingdom of Great Britain and Northern Ireland asked on

Simple Javascript Score Object

I want to keep a simple score using Javascript:

 var score = [
    {name: "spring", score: 0},
    {name: "summer", score: 0},
    {name: "autumn", score: 0},
    {name: "winter", score: 0}
];

Open in new window



I have 4 questions and after each question I want to increase the result...

function questionCalc(number) {
	console.log(number);
	if (number == 1)
		spring ++;
	if (number == 2)
		summer ++;
	if (number == 3)
		autumn ++;
	if (number == 4)
		winter ++;
	console.log("RUNNING RESULTS Spring: "+spring+" Summer: "+summer+" Autumn: "+autumn+" Winter: "+winter);
}

Open in new window


I then want to show the result:

				var scores = [];

				var highestScore = -1, winners = [];
				for (var i = 0; i < scores.length; i++) {
				    if (scores[i] > highestScore) {
				        winners = [i];
				        highestScore = scores[i];
				    } else if (scores[i] == highestScore) {
				        winners.push(i);
				    }
				}

				if (winners.length == 1) {
				    alert("1 winner");
				} else {
				    alert("multiple winners");
				}

Open in new window


Can someone help with the questionCalc function, and perhaps look over my idea.

Thanks

Steve
JavaScript

Avatar of undefined
Last Comment
Kelvin McDaniel

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Michael Vasilevsky

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

@Michael - bear in mind arrays are 0 indexed so
score[num].score++;

Open in new window

Should probably be
score[num-1].score++;

Open in new window

I see a potential problem with this code
var scores = [];
var highestScore = -1, winners = [];
// SOMETHING NEEDS TO HAPPEN TO scores HERE
//     OR ELSE THIS FOR LOOP IS NEVER GOING TO RUN
for (var i = 0; i < scores.length; i++) {
  if (scores[i] > highestScore) {
    winners = [i];
    highestScore = scores[i];
  } 
  else if (scores[i] == highestScore) {
    winners.push(i);
  }
}

Open in new window

SOLUTION
Kelvin McDaniel

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61