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
Steve TinsleyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael VasilevskySolutions ArchitectCommented:
Your score variable is an array of objects, so you can reference each object with the array's index as so:

function questionCalc(num) {
	score[num].score++;
	console.log("RUNNING RESULTS Spring: " + score[0].score + " Summer: " + score[1].score + " Autumn: " + score[2].score + " Winter: " + score[3].score);
}

Open in new window


See working example here

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
@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

Kelvin McDanielSr. DeveloperCommented:
Here's how I would do this...

First, I'd simplify the scores array so that access is trivial and easy to know exactly what I'm dealing with, and when. I've also got a couple of variables that will be used to show the final score.
var rounds = 1;
var maxRounds = 4;

var names = ["Spring", "Summer", "Autumn", "Winter"];
var winners = [];

var scores = [];
names.forEach(function(current) {
  scores.push({ name: current, score: 0 });
});

Open in new window


With this change, the questionCalc function simplifies a bit as well...
// *** IMPORTANT NOTE: 
// You need to ensure that 'number' is zero-based and smaller than the scores (or names) array length.
function questionCalc(number) { 
	if(rounds === 1) {
		winners = [];
		scores.forEach(function(current) {
			current.score = 0;
		});
	}
	
	scores[number].score++;

	var results = "RUNNING RESULTS ";
	scores.forEach(function(current) {
		results += current.name + ": " + current.score + " ";
	});
	console.log(results.trim());
	
	if(rounds === maxRounds) {
		determineWinner();
		rounds = 1;
	} else {
		rounds++;
  }
}

Open in new window


Finally, a simple descending sort on the scores array makes determining the winner very easy.
function determineWinner() {
	scores.sort(function(a, b) {
		return b.score - a.score;
	});

	scores.forEach(function(current) {
		if (current.score === scores[0].score) {
			winners.push(current);
		}
	});

	var multipleWinners = winners.length > 1;
	console.log((multipleWinners ? "multiple" : "1") + " winner" + (multipleWinners ? "s" : "") + "... ");
	winners.forEach(function(current) {
		console.log(current.name + "! (score: " + current.score  + ")");
	});
}

// use a button or something to run the function
$("addPoint").click(function(){
	var recipient = Math.floor((Math.random() * maxRounds) + 1);
	questionCalc(recipient);
});

Open in new window


Here's a working Fiddle (with some minor updates and obligatory embellishments, of course) that illustrates the action. I noticed that JsFiddle's auto-save functionality interrupts the action sometimes... so it may be useful to pause a second or two between each button click (you'll see what I mean).

Also, I'd normally use the traditional for (var i = 0; i < {array}.length; < i++) construct, but my Fiddle started acting nuts for no reason at all... so I went with what worked (because I was tried and didn't feel like fighting someone else's code).
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.