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

JavaScript按年月和类型分组数组统计leavecount并生成WOH类型

实现方案

原代码问题排查

你写的代码存在几个问题:

  • 字段名引用错误:原数组的年份字段是Year,不是你写的vchYear
  • 只有分组逻辑,没有做leavecount的累加统计
  • 没有处理holidayWork不为0时的WOH类型单独统计逻辑
  • 数据结构拼接逻辑错误,和要求的输出格式不匹配

正确实现代码

const result = leaves.reduce((acc, curr) => {
  // 生成 月份+年份 的分组key
  const dateKey = `${curr.mon} ${curr.Year}`
  // 初始化当前月份的分组容器
  if (!acc[dateKey]) {
    acc[dateKey] = {}
  }

  // 优先判断是否为节假日加班,统计WOH类型
  if (curr.holidayWork > 0) {
    acc[dateKey]['WOH'] = (acc[dateKey]['WOH'] || 0) + curr.leavecount
  } else {
    // 正常统计各请假类型的天数
    const leaveType = curr.vchLeaveTypeAlias
    if (leaveType) {
      acc[dateKey][leaveType] = (acc[dateKey][leaveType] || 0) + curr.leavecount
    }
  }
  return acc
}, {})

// 转换为要求的输出格式
const output = [
  Object.fromEntries(
    Object.entries(result).map(([dateKey, typeCounts]) => {
      return [
        dateKey,
        Object.entries(typeCounts).map(([type, count]) => ({ [type]: count }))
      ]
    })
  )
]

此时output变量的值就是你要求的预期输出格式。

实现逻辑说明

  • 第一轮reduce先做累加统计,用对象存储每个月份下各类型的总天数,比直接用数组存储更方便做累加查找,不需要每次遍历数组匹配类型
  • 先判断holidayWork字段,有值的情况优先归到WOH类型统计
  • 最后做格式转换,把每个月份下的统计对象转成要求的数组结构,外层包数组得到最终结果

内容的提问来源于stack exchange,提问作者sadique mohammed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:45:03