views:

195

answers:

3

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!

+1  A: 

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
Ryan Cook
A few suggestions:- Note that the "result" var should really be an object, not an Array, as using object properties on an array often confuses things.- It is good practice to use hasOwnProperty when using the for..in construct.
J c
- The for..in construct may not work as you expect on the "choices" array.- The if statement should really be checking for === undefined, rather than relying on (undefined == null) being true.
J c
Thanks, I made a small edit from your suggestions
Ryan Cook
+2  A: 

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.

J c
This works perfectly. Thank you!
Sean
A: 

Sort the array first, then you can make a single sweep to count occurrences (similar to Ryan's suggestion above).

joel.neely