javascript - 统计数组中的重复项

标签 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

感谢您的帮助!

最佳答案

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

关于javascript - 统计数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900591/

相关文章:

javascript - Parse.com 的 Stripe 云代码模块有限制吗?

javascript - jQuery 停止 Action "breaks"动画

arrays - 在检查数组 1 中的特定条件后,如何将一个数组(数组 1)中的元素添加到另一个数组(数组 2)中?

c# - 将列表<int> 转换为连接的整数字符串?

Java:字符串数组的选择排序

c - 仅根据第一列对C中的二维数组进行排序

perl - 为什么版本排序顺序颠倒了?

javascript - 使用 Swift 在 HTML 中单击一个按钮

arrays - 对J Tally的误解(#)

javascript - css 属性仅适用于代码 - javascript