You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计JavaScript对象数组中userID子属性的出现频率

方案1 直接修改现有函数

仅调整对比逻辑,读取数组元素的userID属性和目标值对比即可:

function getOccurrence(array, targetUserId) {
   var count = 0;
   array.forEach((item) => (item.userID === targetUserId && count++));
   return count;
}

// 调用示例
console.log(getOccurrence(arr, "7d21e968-f32a-4cb9-a0db-dd98d1d2973a")); // 输出 1

方案2 通用属性统计函数

如果后续需要统计其他属性的出现次数,可以把属性名设为入参,提升函数复用性:

function getOccurrenceByProp(array, propName, targetValue) {
  let count = 0;
  array.forEach(item => {
    if (item[propName] === targetValue) count++
  })
  return count
}

// 统计指定userID的出现次数
console.log(getOccurrenceByProp(arr, 'userID', '7d21e968-f32a-4cb9-a0db-dd98d1d2973a'))
// 也可直接统计其他属性,比如tag的出现次数
console.log(getOccurrenceByProp(arr, 'tag', 'REPORT_CREATE')) // 输出 2

方案3 批量生成全量频率表

如果需要频繁查询不同userID的出现次数,可一次性遍历数组生成频率映射表,后续查询时间复杂度为O(1),性能更高:

const userIdCountMap = arr.reduce((map, item) => {
  const userId = item.userID
  map[userId] = (map[userId] || 0) + 1
  return map
}, {})

// 直接取值查询即可
console.log(userIdCountMap['7d21e968-f32a-4cb9-a0db-dd98d1d2973a']) // 1
console.log(userIdCountMap['不存在的ID'] || 0) // 无匹配时默认返回0

内容的提问来源于stack exchange,提问作者Henrique Monteiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:45:05