How to usethe Object.entries method in Javascript

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 ]

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

Similar Reads

Approach 1: Using the Object.entries method

...

Apporach 2: Using For Loop and If condtions

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