统计数组中单词出现次数并返回对象数组的实现问题
统计数组元素出现次数并转换为指定格式
首先先修正你代码里的两处小问题:
- 数组声明需要变量名,比如
const fruits = ['apple', 'orange', 'apple', 'apple', 'pear', 'pear'],不能直接写const = [...] - 期望结果里的
{fruit: pear, numberOfOccurences: 2}要改成{fruit: 'pear', numberOfOccurences: 2},pear是字符串必须加引号
下面给你两种可行的解决方法:
方法一:使用 reduce(你尝试过的方案,修正后实现)
reduce 是处理这类统计需求的常用方法,核心是用一个对象临时存储统计结果,最后转换为目标数组:
const fruits = ['apple', 'orange', 'apple', 'apple', 'pear', 'pear']; const occurrences = Object.values(fruits.reduce((acc, fruit) => { // 若当前水果未在累加器中,初始化符合要求的对象 if (!acc[fruit]) { acc[fruit] = { fruit, numberOfOccurences: 0 }; } // 计数递增 acc[fruit].numberOfOccurences++; return acc; }, {})); console.log(occurrences); // 输出:[{fruit: 'apple', numberOfOccurences: 3}, {fruit: 'orange', numberOfOccurences: 1}, {fruit: 'pear', numberOfOccurences: 2}]
代码说明:
reduce的初始值是一个空对象{},用来临时存储每个水果的统计条目- 遍历数组时,检查当前水果是否已在累加器中:
- 不存在则创建一个包含
fruit和初始计数0的对象 - 存在则直接将对应条目的计数加1
- 不存在则创建一个包含
- 最后用
Object.values()提取累加器对象中的所有值,转换为数组,就是你要的结果
方法二:使用 Map(更直观的统计方式)
用 Map 存储键值对(水果名-出现次数),最后再转换为目标格式:
const fruits = ['apple', 'orange', 'apple', 'apple', 'pear', 'pear']; const fruitMap = new Map(); // 遍历数组统计次数 fruits.forEach(fruit => { fruitMap.set(fruit, (fruitMap.get(fruit) || 0) + 1); }); // 将Map转换为目标数组格式 const occurrences = Array.from(fruitMap, ([fruit, count]) => ({ fruit, numberOfOccurences: count })); console.log(occurrences); // 输出与上面一致
代码说明:
- 初始化
Map对象,遍历数组时用get获取当前水果的计数(不存在则取0),加1后用set更新 - 用
Array.from()将Map的键值对转换为数组,同时把每个键值对映射成指定结构的对象
内容的提问来源于stack exchange,提问作者user19031425
相关产品推荐
相关产品推荐

