JavaScript用filter/map/reduce实现银行交易数据3项统计任务
JavaScript 交易数据统计实现方案
以下实现仅使用filter/map/reduce三个指定API完成,默认交易数据中replenishment类型为存入,payment类型为支取/取现。
1. task_1 实现:统计交易次数TOP3月份
核心思路是用reduce按年月分组统计次数,直接在分组时保留年月字段,避免后续关联丢失信息:
function task_1(arr) { // 按年月分组统计交易次数 const monthCountMap = arr.reduce((acc, item) => { const key = `${item.year}-${item.month}` if (!acc[key]) { acc[key] = { year: item.year, month: item.month, opsCount: 0 } } acc[key].opsCount += 1 return acc }, {}) // 转数组后按交易次数降序排列,取前3条 return Object.values(monthCountMap) .sort((a, b) => b.opsCount - a.opsCount) .slice(0, 3) }
2. task_2 实现:指定年月的月度统计数据
先筛选目标月份交易,再用reduce汇总收支金额,最后计算对应维度字段:
function task_2(year, month, arr) { // 筛选指定年月的所有交易 const targetTrades = arr.filter(item => item.year === year && item.month === month) // 统计总存入、总支取金额 const { totalIn, totalOut } = targetTrades.reduce((acc, item) => { item.type === 'replenishment' ? acc.totalIn += item.amount : acc.totalOut += item.amount return acc }, { totalIn: 0, totalOut: 0 }) // 计算各统计字段 const monthBalance = totalIn - totalOut const withdrawalRate = totalIn === 0 ? 0 : Number((totalOut / totalIn).toFixed(4)) // 计算用户等级 let rank = 'Bronze' if (withdrawalRate < 0.15) rank = 'Gold' else if (withdrawalRate < 0.3) rank = 'Silver' // 拼接月末日期,如需真实月末可替换为new Date(year, month, 0).getDate()获取当月天数 const date = `${year}-${String(month).padStart(2, '0')}-31` return { date, monthBalance, monthWithrawal: totalOut, withdrawalRate, rank } }
3. task_3 实现:全周期月度累计统计
先分组得到所有年月的交易集合,排序后复用task_2计算月度数据,累加得到累计余额:
function task_3(arr) { // 按年月分组收集所有交易 const monthGroup = arr.reduce((acc, item) => { const key = `${item.year}-${item.month}` if (!acc[key]) { acc[key] = { year: item.year, month: item.month, trades: [] } } acc[key].trades.push(item) return acc }, {}) // 按年月升序排序 const sortedMonths = Object.values(monthGroup).sort((a, b) => a.year - b.year || a.month - b.month) // 遍历计算月度统计+累计余额 let totalBalance = 0 return sortedMonths.map(item => { const monthStat = task_2(item.year, item.month, arr) totalBalance += monthStat.monthBalance return { ...monthStat, totalBalance } }) }
兼容处理说明
- 存入总金额为0时,支取比例默认设为0,避免除以0报错
- 月末日期可根据需求替换为真实日期计算逻辑,不影响核心统计逻辑
内容的提问来源于stack exchange,提问作者JohnSmith
相关产品推荐
相关产品推荐

