按code分组对象数组时,如何确保home侧统计值优先存入stats数组
需求实现与代码优化
原始数据集
[ { "teamFK": 8650, "code": "yellow_cards", "typeId": 554, "value": "5", "side": "home" }, { "teamFK": 8650, "code": "goals", "typeId": 554, "value": "1", "side": "home" }, { "teamFK": 8990, "code": "yellow_cards", "typeId": 555, "value": "2", "side": "away" }, { "teamFK": 8990, "code": "goals", "typeId": 555, "value": "0", "side": "away" } ]
目标输出
按code字段分组,且side为home的统计值始终排在stats数组首位:
{ "stats": [ { "name": "yellow_cards", "stats": ["5","2"] }, { "name": "goals", "stats": ["1","0"] } ] }
注:原目标输出中goals的stats数组值应为["1","0"],推测是笔误
现有基础代码
const groupedStats = Object.entries( query.reduce((acc, { typeId, value, code, side }) => { if (!acc[code]) { acc[code] = []; } acc[code].push(value); return acc; }, {}), ).map(([name, stats]) => ({ name, stats }));
优化后的代码
const groupedStats = { stats: Object.entries( query.reduce((acc, { value, code, side }) => { // 初始化分组数组,预留home(索引0)和away(索引1)的固定位置 if (!acc[code]) { acc[code] = [null, null]; } // 根据side字段确定值的存放索引,确保home值始终在首位 const index = side === 'home' ? 0 : 1; acc[code][index] = value; return acc; }, {}) ).map(([name, stats]) => ({ name, stats })) };
优化说明
- 初始化分组数组时直接创建长度为2的数组,分别对应
home和away的固定位置 - 通过
side字段判断值的存放索引,home对应索引0,away对应索引1 - 不受原始数据遍历顺序影响,始终保证
home统计值排在stats数组第一位,完全符合需求
内容的提问来源于stack exchange,提问作者robinhood
相关产品推荐
相关产品推荐

