How to useObject.entries() and Reduce() in Javascript
Using Object.entries() and reduce() to find the second most repeated word involves counting word frequencies with reduce(), converting the object into an array of entries, sorting it by frequency, and returning the second entry.
Example:
function findSecondMostRepeatedWord(sequence) {
const frequency = sequence.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {});
const sorted = Object.entries(frequency).sort((a, b) => b[1] - a[1]);
return sorted[1] ? sorted[1][0] : null;
}
const sequence = ["apple", "banana", "banana", "apple", "cherry", "banana", "cherry"];
console.log(findSecondMostRepeatedWord(sequence)); // Output: "apple"
Output
apple
JavaScript Program to Find Second Most Repeated Word in a Sequence
Finding the second most repeated word in a sequence involves analyzing a given text or sequence of words to determine which word appears with the second-highest frequency. This task often arises in natural language processing and text analysis. To solve it, we need to parse the input sequence, count word frequencies, and identify the word with the second-highest count.
Examples:
Input : {"1", "2", "1", "1", "2", "3"}
Output : "2"
Input : {"a", "b", "c", "a", "a", "b"}
Output : "b"
Table of Content
- Approach 1: Using Map() in JavaScript
- Approach 2: Using Set() in JavaScript
- Approach 3: Using Object.entries() and Reduce()