计算阵列中重复的项目

时间:2012-06-05 15:52:44

标签: javascript arrays sorting

我有以下JavaScript数组:

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";

如何计算重复的项目,以便输出如下:

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

@Tyson:不应使用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.

答案 1 :(得分:0)

我不是一个javascript开发人员,但基于this关于js中哈希表的文章,看起来你会想要如下内容:

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 />");
}