如何用RxJS的reduce、filter算子实现物品买卖次数分组统计函数?
基于RxJS实现物品买卖次数分组统计
需要实现一个函数,对指定输入数据按物品分组,统计每种物品的**Sell(卖出)和Buy(买入)**次数,输出预期格式的结果。目前已尝试使用RxJS的reduce和filter算子,寻求可行实现方案。
函数输入示例
[ { "Item": "Pen", "Action": "Sell" }, { "Item": "Pen", "Action": "Sell" }, { "Item": "Pen", "Action": "Buy" }, { "Item": "Pencil", "Action": "Sell" }, { "Item": "Pencil", "Action": "Sell" }, { "Item": "Pencil", "Action": "Buy" }, { "Item": "Pencil", "Action": "Buy" } ]
预期输出
[ { "Item": "Pen", "sellCount": 2, "buyCount": 1 }, { "Item": "Pencil", "sellCount": 2, "buyCount": 2 } ]
实现方案
结合RxJS的groupBy、reduce和mergeMap算子即可实现需求,核心逻辑是先按物品分组,再在每个分组内累计统计买卖次数,最后合并结果:
import { from } from 'rxjs'; import { groupBy, mergeMap, reduce, toArray } from 'rxjs/operators'; // 示例输入数据 const inputData = [ { "Item": "Pen", "Action": "Sell" }, { "Item": "Pen", "Action": "Sell" }, { "Item": "Pen", "Action": "Buy" }, { "Item": "Pencil", "Action": "Sell" }, { "Item": "Pencil", "Action": "Sell" }, { "Item": "Pencil", "Action": "Buy" }, { "Item": "Pencil", "Action": "Buy" } ]; // 实现逻辑 from(inputData).pipe( // 按物品名称分组 groupBy(item => item.Item), // 处理每个分组的统计逻辑 mergeMap(group$ => group$.pipe( reduce((acc, curr) => { // 初始化当前物品的统计对象 if (!acc.Item) { acc.Item = group$.key; acc.sellCount = 0; acc.buyCount = 0; } // 根据操作类型累加计数 curr.Action === 'Sell' ? acc.sellCount++ : acc.buyCount++; return acc; }, {}) )), // 将所有统计结果收集为数组 toArray() ).subscribe(result => { console.log(result); // 输出与预期格式一致的数组 });
逻辑说明
groupBy:把原始数据流按Item字段拆分为多个子数据流,每个子流对应一种物品的所有操作记录;reduce:在每个子流内迭代,累计当前物品的卖出、买入次数,初始值为一个空对象,逐步更新计数;mergeMap:将各个分组的统计结果合并回一个统一的数据流;toArray:把数据流中的所有统计对象收集为一个数组,直接得到预期的输出格式。
内容的提问来源于stack exchange,提问作者TechLad
相关产品推荐
相关产品推荐

