Simple Javascript Score Object

Steve Tinsley
Steve Tinsley used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Solutions Architect
Commented:
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
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@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

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).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial