You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

统计数组中单词出现次数并返回对象数组的实现问题

统计数组元素出现次数并转换为指定格式

首先先修正你代码里的两处小问题:

  • 数组声明需要变量名,比如 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}]

代码说明:

  1. reduce 的初始值是一个空对象 {},用来临时存储每个水果的统计条目
  2. 遍历数组时,检查当前水果是否已在累加器中:
    • 不存在则创建一个包含 fruit 和初始计数 0 的对象
    • 存在则直接将对应条目的计数加1
  3. 最后用 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);
// 输出与上面一致

代码说明:

  1. 初始化 Map 对象,遍历数组时用 get 获取当前水果的计数(不存在则取0),加1后用 set 更新
  2. 用 Array.from() 将 Map 的键值对转换为数组,同时把每个键值对映射成指定结构的对象

内容的提问来源于stack exchange,提问作者user19031425

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:22:15