Skip to content

Latest commit

 

History

History
28 lines (18 loc) · 809 Bytes

countOccurrences.md

File metadata and controls

28 lines (18 loc) · 809 Bytes
标题 标签
countOccurrences(计算数组项出现的次数) array,intermediate(数组,两者之间的)

计算数组中某个值的出现次数。

  • 每次在数组中遇到特定值时,使用 Array.prototype.reduce() 递增计数器。

代码如下:

const countOccurrences = (arr, val) =>
  arr.reduce((r, v) => (v === val ? r + 1 : r), 0);

调用方式:

countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

应用场景

结果如下:

<iframe src="codes/javascript/html/countOccurrences.html"></iframe>