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:

JavaScript
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()

Similar Reads

Approach 1: Using Map() in JavaScript

This approach involves iterating through the words in the sequence and using a hash map to count their frequencies. By maintaining two variables to track the most repeated and second most repeated words, we can efficiently identify the second most repeated word....

Approach 2: Using Set() 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....

Approach 3: Using Object.entries() and Reduce()

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....