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

使用Lodash获取数组中出现频率最高的元素

Solution: Find Most Frequent Element with Lodash

Hey there! You're already using the right Lodash methods—let's piece them together to get the result you need. Here's a step-by-step breakdown tailored to your example:

Step-by-Step Implementation

First, let's start with your sample array:

const array = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

1. Count Element Occurrences

Use _.countBy() to generate an object where keys are array elements and values are their occurrence counts:

const countMap = _.countBy(array);
// Result: { '2': 2, '3': 4, '4': 1, '9': 1, 'a': 5 }

2. Convert to Key-Value Pairs

Turn the count object into an array of [element, count] pairs with _.entries()—this makes it easier to sort/filter by count:

const countEntries = _.entries(countMap);
// Result: [['2',2], ['3',4], ['4',1], ['9',1], ['a',5]]

3. Find the Most Frequent Entry

Use _.maxBy() to pick the entry with the highest count. We'll destructure the pair to focus on the count value:

const mostFrequentPair = _.maxBy(countEntries, ([_, count]) => count);
// Result: ['a', 5]

4. Format the Result

Extract the element and count to get your desired output string:

const result = `${mostFrequentPair[0]} (${mostFrequentPair[1]}次)`;
console.log(result); // Output: a (5次)

Simplified Chain Version

You can combine all steps into a clean Lodash chain for brevity:

const _ = require('lodash');

const array = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

const mostFrequentPair = _.chain(array)
  .countBy()
  .entries()
  .maxBy(([_, count]) => count)
  .value();

const result = `${mostFrequentPair[0]} (${mostFrequentPair[1]}次)`;
console.log(result); // a (5次)

Handling Ties (Multiple Elements with Same Max Count)

If your array has multiple elements with the highest occurrence count, you can adjust the code to return all of them:

const _ = require('lodash');

const array = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 2, 4, 9, 3]; // a and 3 both occur 4 times

const countMap = _.countBy(array);
const maxCount = _.max(_.values(countMap));
const mostFrequentElements = _.keys(countMap).filter(key => countMap[key] === maxCount);

// Print all top elements
mostFrequentElements.forEach(element => {
  console.log(`${element} (${maxCount}次)`);
});
// Output:
// a (4次)
// 3 (4次)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:14:18