如何修改数组reduce方法输出仅保留频次数值数组?
调整reduce统计代码输出为频次数组
问题描述
现有数组:
['Online Learning', 'Online Learning', 'Online Learning', 'Communications', 'Communications', 'Intranet']
使用以下代码统计元素出现频次:
const catsReduced = cats.reduce((acc: any, currentValue: any) => (acc[currentValue] = (acc[currentValue] || 0) + 1, acc), {});
当前输出为对象格式:
{Online Learning: 3, Communications: 2, Intranet: 1}
需要修改代码,使输出变为数字类型数组:
[3,2,1]
解决方案
只需在原reduce统计逻辑外,嵌套Object.values()方法提取对象的属性值即可:
const cats = ['Online Learning', 'Online Learning', 'Online Learning', 'Communications', 'Communications', 'Intranet']; const catsReduced = Object.values( cats.reduce((acc: any, currentValue: any) => { acc[currentValue] = (acc[currentValue] || 0) + 1; return acc; }, {}) );
说明
原reduce代码已经完成了频次统计,只是结果以键值对对象存储。Object.values()会提取对象的所有属性值并返回数组,且现代JS环境中对象属性会保留首次插入顺序,因此得到的数组顺序和原数组元素首次出现的顺序完全匹配,符合需求。
内容的提问来源于stack exchange,提问作者NightTom
相关产品推荐
相关产品推荐

