Link to home
Start Free TrialLog in
Avatar of Steve Tinsley
Steve TinsleyFlag 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
ASKER CERTIFIED SOLUTION
Avatar of Michael Vasilevsky
Michael Vasilevsky
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial