Open In App

JavaScript Program to Find k Most Frequent Elements in Array

Last Updated : 28 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are given an input array with the elements and k value. Our task is to find out the most frequent elements in the array as per the k value using JavaScript. Below we have added the example for better understanding.

Example:

Input: array = [7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9] , K = 4
Output: [5, 7, 11, 10] or [5, 7, 11, 2]
Explanation:
5 -> 3 Frequency
7 -> 2 Frequency
11 -> 2 Freqency
2 -> 1 Frequency
10 -> 1 Frequency

So, we can find these frequent elements using the below approach:

Approach 1: Using the Object.entries method

The Object.entries method in the JavaScript is the builtin method that is used here to convert the frequency values of the input array by the user in the Key Value pair. When this is been converted to key-value pair, we will performing the sorting of this frequencies, as we need to print the most frequent elements, so we are sorting in decending order. According to the k value the most highest frequencies are then shown to the user.

Syntax:

let value= Array.from(Object.entries()).sort((a, b) => b[1] - a[1]);

Example: In this example, we have used printed the k most frequent elements in array using Object.entries method.

Javascript




let array = [
    7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9,
];
let K = 4;
function kFreq() {
    let fMap = new Map();
    array.forEach((n) => {
        if (fMap.has(n)) {
            fMap.set(
                n,
                fMap.get(n) + 1
            );
        } else {
            fMap.set(n, 1);
        }
    });
    let sort = Array.from(
        fMap.entries()
    ).sort((a, b) => b[1] - a[1]);
    let res = sort
        .slice(0, K)
        .map((temp) => temp[0]);
    console.log(res);
}
kFreq();


Output

[ 5, 7, 11, 10 ]

Apporach 2: Using For Loop and If condtions

The for loop is used to iterate over the elements or array elements entered by the user. The If conditons are used to check the frequency of elements rather than using any inbuilt function for sorting like Approach 1. Using this apporach, we can get the k frequent items by writing the code using for loops and if-else condtional statements. We have also validated the input of k, when the user enters invalid value then the alert box is been shown to the user.

Example: In this example, we have used printed the k most frequent elements in array using for loop and if conditions.

Javascript




function freqUsingFor(ipArr, kEle) {
    let mapFreq = {};
    let FreqEle = [];
    for (
        let i = 0;
        i < ipArr.length;
        i++
    ) {
        let temp = ipArr[i];
        if (mapFreq[temp]) {
            mapFreq[temp]++;
        } else {
            mapFreq[temp] = 1;
        }
        if (
            FreqEle.indexOf(temp) === -1
        ) {
            FreqEle.push(temp);
        }
        FreqEle.sort((a, b) => {
            return (
                mapFreq[b] - mapFreq[a]
            );
        });
        if (FreqEle.length > kEle) {
            FreqEle.pop();
        }
    }
    return FreqEle;
}
let array = [
    7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9,
];
let K = 4;
let result = freqUsingFor(array, K);
console.log(result);


Output

[ 5, 7, 11, 10 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads