如何合并宝可梦类型与精灵数组,按类型统计总power值并输出指定格式
实现代码
function calculateTypePower() { // 生成类型ID到类型名称的映射表,方便后续快速查询 const typeIdToName = pokeTypes.reduce((map, typeItem) => { map[typeItem.uuid] = typeItem.pokemonType return map }, {}) // 按类型ID累加所有宝可梦的power总值 const typePowerTotal = pokemons.reduce((total, pokemon) => { const typeId = pokemon.pokemonTypeId total[typeId] = (total[typeId] || 0) + pokemon.power return total }, {}) // 转换为要求的输出格式,且按power总值降序排序 const result = Object.entries(typePowerTotal) .map(([typeId, power]) => ({ [typeIdToName[typeId]]: power })) .sort((a, b) => Object.values(b)[0] - Object.values(a)[0]) return result } // 调用输出结果 console.log(calculateTypePower())
逻辑说明
- 先将分类数组转换为
ID: 类型名的映射结构,避免后续重复遍历分类数组查询类型名称 - 累加阶段直接统计每个类型的power总和,不需要存储单个宝可梦的冗余数据
- 最后转换格式后按power值降序排序,和你给出的预期输出结构完全一致
内容的提问来源于stack exchange,提问作者user16963129
相关产品推荐
相关产品推荐

