Counting Results in an Array
-
20-08-2019 - |
Question
By means of a regular expression and Greasemonkey I have an array of results that looks like:
choice1, choice2, choice3, choice3, choice1, etc..
My question is how do I tally up the choices so I know how many times choice1 is in the array, choice2 is in the array, etc. if I do not know exactly how many choices there are or what they are.
The ultimate goal is to create a Greasemonkey script that stores the number of votes each choice gets over multiple pages (probably using gm_setvalue although I'm open to other ideas.)
Thanks!
Solution
One technique would be to iterate over the choices and increment a counter associated to each unique choice in an object property.
Example:
var choiceCounts = {};
for (var iLoop=0; iLoop < aChoices.length; iLoop++) {
var keyChoice = aChoices[iLoop];
if (!choiceCounts[keyChoice]) {
choiceCounts[keyChoice] = 1;
} else {
choiceCounts[keyChoice]++;
} //if
} //for
You then have an object with properties equal to the number of times that the property existed in the array.
OTHER TIPS
Not 100% sure what your looking for, but I think this is it.
// Original data
var choices = [
"choice 1",
"choice 1",
"choice 2",
"choice 3",
"choice 3",
"choice 3",
"choice 3",
"choice 3",
"choice 3",
"choice 4",
"choice 4",
"choice 4"];
//Create the results array
var result = new Object();
for (var choice in choices) {
if (result[choices[choice]] === undefined)
result[choices[choice]] = 1;
else
result[choices[choice]]++;
}
//Print result
var str = "";
for (var item in result)
str += item + ": " + result[item] + "<br />";
document.getElementById("resultDiv").innerHTML = str;
Output:
choice 1: 2
choice 2: 1
choice 3: 6
choice 4: 3
Sort the array first, then you can make a single sweep to count occurrences (similar to Ryan's suggestion above).