Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the most frequent word(s) in an array using JavaScript
In JavaScript, finding the most frequent words in an array is a common problem that involves counting occurrences and sorting by frequency. This article demonstrates how to find the top N most frequent words from an array of strings.
Problem Statement
We need to write a JavaScript function that takes an array of lowercase English strings and returns the most frequent elements. The function should:
- Accept an array of strings as the first parameter
- Accept a number specifying how many top frequent words to return
- Sort results by frequency (highest to lowest)
- For words with equal frequency, sort alphabetically
Example Input and Output
Input:
const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"]; const num = 4;
Expected Output:
["the", "is", "sunny", "day"]
Explanation: "the" appears 4 times, "is" appears 3 times, "sunny" appears 2 times, and "day" appears 1 time.
Solution Approach
The solution involves three main steps:
- Count frequencies: Use an object to store word counts
- Extract and sort keys: Sort by frequency (descending), then alphabetically for ties
- Return top N results: Use slice() to get the required number of words
Complete Implementation
const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"];
const num = 4;
const mostFrequent = (arr = [], num = 1) => {
// Step 1: Count word frequencies
const frequencyMap = {};
for (let i = 0; i < arr.length; i++) {
if (frequencyMap[arr[i]]) {
frequencyMap[arr[i]]++;
} else {
frequencyMap[arr[i]] = 1;
}
}
// Step 2: Get all unique words
let words = [];
for (let word in frequencyMap) {
words.push(word);
}
// Step 3: Sort by frequency (descending) and alphabetically for ties
words = words.sort((a, b) => {
if (frequencyMap[a] === frequencyMap[b]) {
// Same frequency: sort alphabetically
return a > b ? 1 : -1;
} else {
// Different frequency: sort by count (highest first)
return frequencyMap[b] - frequencyMap[a];
}
}).slice(0, num);
return words;
};
console.log(mostFrequent(arr, num));
[ 'the', 'is', 'sunny', 'day' ]
How It Works
- Frequency Counting: We iterate through the array and build a frequency map where keys are words and values are their counts
- Sorting Logic: The custom comparator first checks if frequencies are equal. If so, it sorts alphabetically; otherwise, it sorts by frequency in descending order
-
Result Selection: We use
slice(0, num)to get only the top N most frequent words
Alternative Using Modern JavaScript
Here's a more concise version using ES6+ features:
const mostFrequentModern = (arr, num) => {
// Count frequencies using reduce
const freq = arr.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {});
// Sort and return top N
return Object.keys(freq)
.sort((a, b) => freq[b] - freq[a] || a.localeCompare(b))
.slice(0, num);
};
const testArr = ["apple", "banana", "apple", "cherry", "banana", "apple"];
console.log(mostFrequentModern(testArr, 2));
[ 'apple', 'banana' ]
Key Points
- Use objects as hash maps for efficient frequency counting
- Custom sort comparators handle multiple sorting criteria
-
localeCompare()provides reliable alphabetical sorting -
slice()efficiently limits results to the required count
Conclusion
Finding the most frequent words involves counting occurrences and applying multi-criteria sorting. The key is using a frequency map and a custom comparator that handles both frequency and alphabetical ordering for consistent results.
