# Finding the most frequent word(s) in an array using JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in an array, arr, of strings of English lowercase alphabets as the first argument. The second argument to our function is a number, num (num < length of arr).

Our function is supposed to return the num most frequent elements in the array arr.

The answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

For example, if the input to the function is

Input

const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"];
const num = 4;

Output

const output = ["the", "is", "sunny", "day"];

Output Explanation

"the", "is", "sunny" and "day" are the four most frequent words,

with the number of occurrences being 4, 3, 2 and 1 respectively.

## Example

Following is the code −

Live Demo

const arr = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"];
const num = 4;
const mostFrequent = (arr = [], num = 1) => {
const map = {};
let keys = [];
for (let i = 0; i < arr.length; i++) {
if (map[arr[i]]) {
map[arr[i]]++;
} else {
map[arr[i]] = 1;
}
}
for (let i in map) {
keys.push(i);
}
keys = keys.sort((a, b) => {

if (map[a] === map[b]) {

if (a > b) {
return 1;
} else {
return -1;
}
}
else {
return map[b] - map[a];
}
})
.slice(0, num);
return keys;
};
console.log(mostFrequent(arr, num));

## Output

[ 'the', 'is', 'sunny', 'day' ]