How to useSet() in JavaScript in Javascript
Set() approach is to count the occurrences of each word in the array using a Map, then find the second most repeated word by comparing the occurrence counts. It iterates through the array to count word occurrences and efficiently identifies the second most repeated word using a Map data structure.
Syntax:
let occurrences = new Map();
occurrences.set()
Example: Below is the implementation of the above approach.
// Function to find the second most repeated word
function findSecondMostRepeatedWordInArray(words) {
// Store all the words with their occurrences
let occurrences = new Map();
for (let i = 0; i < words.length; i++) {
if (occurrences.has(words[i])) {
occurrences.set(words[i],
occurrences.get(words[i]) + 1);
} else {
occurrences.set(words[i], 1);
}
}
// Find the second largest occurrence
let firstMax =
Number.MIN_VALUE,
secondMax = Number.MIN_VALUE;
for (let [key, value] of occurrences) {
if (value > firstMax) {
secondMax = firstMax;
firstMax = value;
} else if (value > secondMax
&& value !== firstMax) {
secondMax = value;
}
}
// Return the word with
// an occurrence equal to secondMax
for (let [key, value] of occurrences) {
if (value === secondMax) {
return key;
}
}
}
// Driver program
let wordsArray = ["a", "b", "c", "a", "a", "b"];
console.log(findSecondMostRepeatedWordInArray(wordsArray));
Output
b
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()