2

I have the following JavaScript array:

var President = new Array();
President[0]="Thomas Jefferson";
President[1]="Thomas Jefferson";
President[2]="Thomas Jefferson";
President[3]="Thomas Jefferson";
President[4]="Thomas Jefferson";
President[5]="Thomas Jefferson";
President[6]="Thomas Jefferson";
President[7]="Thomas Jefferson";
President[8]="Thomas Jefferson";
President[9]="Thomas Jefferson";
President[10]="Thomas Jefferson";
President[11]="Thomas Jefferson";
President[12]="Thomas Jefferson";
President[13]="James Madison";
President[14]="James Madison";
President[15]="James Madison";
President[16]="James Madison";
President[17]="James Madison";
President[18]="James Madison";
President[19]="James Madison";
President[20]="Abraham Lincoln";
President[21]="Abraham Lincoln";
President[22]="Abraham Lincoln";
President[23]="Abraham Lincoln";
President[24]="Abraham Lincoln";
President[25]="George Washington";

How to I tally up the repeated items so that the output is as follows:

Thomas Jefferson: 13
James Madison: 7
Abraham Lincoln: 5
George Washington: 1

Thanks for your help!

zdebruine
  • 3,687
  • 6
  • 31
  • 50
  • FYI, there is a "Code Sample" formatting button in the text editor when posting a question. Also, what have you tried so far? – Colin Brock Jun 05 '12 at 15:57
  • 1
    possible duplicate of [Counting occurences of Javascript array elements](http://stackoverflow.com/questions/5667888/counting-occurences-of-javascript-array-elements) – j08691 Jun 05 '12 at 16:06

2 Answers2

2

@Tyson : Arrays should not be traversed using for.. in.

  for (var stats = {}, potus, i = President.length; i--;) {
    if (!((potus = President[i]) in stats)
      stats[potus] = 0; // Initialize a new counter
    stats[potus]++;
  }

  // Now stats['Thomas Jefferson'] will be 13 etc.
HBP
  • 15,685
  • 6
  • 28
  • 34
0

I'm not a javascript developer, but based on this article on hash tables in js it looks like you would want something like the following:

var h = new Object();
for (var p in President) {
    if (h.hasItem(p)) {
        h.setItem(p, h.getItem(p) + 1);
    }
    else {
        h.setItem(p, 1);
    }
}

for (var p in h)
{
    document.write(p);
    document.write(":");
    document.write(h.getItem(p));
    document.write("<br />");
}
Tyson
  • 1,685
  • 15
  • 36