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

如何使用JavaScript的.reduce高阶函数统计数组中元素的出现次数?

如何使用JavaScript的.reduce高阶函数统计数组中元素的出现次数?

Hey there! I totally get where you're coming from—.reduce() can feel a bit confusing when you're new to it, but once you get the hang of how it works, it's perfect for counting element occurrences like this. Let's walk through this together.

First, let's recap what .reduce() does: it iterates over each element in the array, and uses an "accumulator" (a value we build up over each iteration) to compute a final result. For our case, we'll use an empty object as the accumulator to store each element and its count.

Here's the code that does exactly what you need:

let array = [1,2,3,4,5,6,7,1,2,3,1,2,3,1,2,3,3,3,3,3,4,98,-546,4];

// 使用reduce统计次数
const occurrenceCounts = array.reduce((acc, currentElement) => {
  // 如果当前元素已经在累加器里,就把计数加1;否则初始化为1
  acc[currentElement] = (acc[currentElement] || 0) + 1;
  // 一定要返回累加器,这样下一次迭代才能继续使用它
  return acc;
}, {}); // 这里的{}是累加器的初始值

console.log(occurrenceCounts);

让我们拆解一下这段代码:

  • acc:这是我们的累加器对象,一开始是空的{}。每一次迭代,我们都会更新它。
  • currentElement:这是数组中当前正在被处理的元素。
  • acc[currentElement] || 0:这个小技巧是说,如果当前元素已经在累加器里存在(有对应的计数值),就用那个值;如果不存在,就用0。然后我们给这个值加1,这样第一次出现的元素会被设为1,之后每次出现都递增计数。

When you run this code, the output will be an object where each key is an element from the array, and the value is how many times it appeared:

{
  "1": 4,
  "2": 4,
  "3": 8,
  "4": 3,
  "5": 1,
  "6": 1,
  "7": 1,
  "98": 1,
  "-546": 1
}

If you want to format the result exactly like you mentioned—1 -> 4 times ; 2 -> 4 times etc.—you can convert that object into a string using Object.entries() and map():

// 转换成你想要的字符串格式
const formattedResult = Object.entries(occurrenceCounts)
  .map(([element, count]) => `${element} -> ${count} times`)
  .join(' ; ');

console.log(formattedResult);
// 输出: "1 -> 4 times ; 2 -> 4 times ; 3 -> 8 times ; 4 -> 3 times ; 5 -> 1 times ; 6 -> 1 times ; 7 -> 1 times ; 98 -> 1 times ; -546 -> 1 times"

小提示:

  • Don't forget to return the accumulator (acc) from the reduce callback—this is crucial, because it passes the updated value to the next iteration.
  • Object.entries() turns our count object into an array of [element, count] pairs, which makes it easy to format with map().

Hope this clears things up for you! Let me know if you have any other questions about .reduce() or JavaScript in general.

备注:内容来源于stack exchange,提问作者Abhijeet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 15:14:53