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); |
[ 5, 7, 11, 10 ]
JavaScript Program to Find k Most Frequent Elements in Array
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:
Table of Content
- Using the Object.entries method in JavaScript
- Using For Loop and If condtions