统计数组中单词出现次数并返回对象数组是前端数据处理中常见的需求,核心逻辑是先遍历数组统计每个单词的出现频次,再将统计结果转换为指定格式的对象数组。

基础实现思路
实现该需求主要分为三个步骤:
- 遍历输入的单词数组,使用对象记录每个单词的出现次数
- 遍历记录频次的对象,将每个单词和对应的次数组合成对象
- 将所有对象放入数组并返回结果
基础代码示例
以下是使用JavaScript实现的基础版本,假设输入的数组元素都是合法的单词,不存在重复空格或特殊字符:
// 定义输入的单次数组
const wordArray = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
// 统计单词出现次数的函数
function countWordsToObjArray(arr) {
// 第一步:统计每个单词的出现次数
const countMap = {};
for (let i = 0; i < arr.length; i++) {
const word = arr[i];
if (countMap[word]) {
countMap[word] += 1;
} else {
countMap[word] = 1;
}
}
// 第二步:将统计结果转换为对象数组
const resultArray = [];
for (const word in countMap) {
resultArray.push({
word: word,
count: countMap[word]
});
}
return resultArray;
}
// 调用函数并输出结果
const result = countWordsToObjArray(wordArray);
console.log(result);
// 输出:[{word: 'apple', count: 3}, {word: 'banana', count: 2}, {word: 'orange', count: 1}]
优化适配场景
实际场景中可能存在单词大小写不一致、包含特殊字符的情况,需要对输入数组做预处理后再统计:
忽略大小写并过滤特殊字符
下面的代码会先将单词转为小写,再过滤掉非字母的字符,再进行统计:
function countWordsAdvanced(arr) {
const countMap = {};
for (let i = 0; i < arr.length; i++) {
// 转为小写并过滤非字母字符
const processedWord = arr[i].toLowerCase().replace(/[^a-z]/g, '');
// 过滤空字符串
if (processedWord === '') continue;
if (countMap[processedWord]) {
countMap[processedWord] += 1;
} else {
countMap[processedWord] = 1;
}
}
const resultArray = [];
for (const word in countMap) {
resultArray.push({
word: word,
count: countMap[word]
});
}
return resultArray;
}
// 测试包含大小写和特殊字符的数组
const testArray = ['Apple!', 'Banana', 'apple', 'Orange-', 'banana', 'APPLE'];
const advancedResult = countWordsAdvanced(testArray);
console.log(advancedResult);
// 输出:[{word: 'apple', count: 3}, {word: 'banana', count: 2}, {word: 'orange', count: 1}]
使用Map优化统计逻辑
ES6引入的Map结构可以更方便地存储键值对,避免对象键名的隐式类型转换问题:
function countWordsWithMap(arr) {
const countMap = new Map();
for (const word of arr) {
const currentCount = countMap.get(word) || 0;
countMap.set(word, currentCount + 1);
}
const resultArray = [];
for (const [word, count] of countMap) {
resultArray.push({ word, count });
}
return resultArray;
}
const mapTestArray = ['cat', 'dog', 'cat', 'bird', 'dog', 'cat'];
const mapResult = countWordsWithMap(mapTestArray);
console.log(mapResult);
// 输出:[{word: 'cat', count: 3}, {word: 'dog', count: 2}, {word: 'bird', count: 1}]
注意事项
- 如果输入的数组包含空字符串,需要根据业务需求决定是否统计,可在遍历时增加判断逻辑
- 对象数组的属性名可以根据需求调整,比如将
word改为name,count改为frequency - 如果数组元素量非常大,基础遍历的性能已经足够,不需要过度优化
JavaScript数组统计单词计数对象数组修改时间:2026-06-29 04:45:19