Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Find the Most Frequent Element in an Array

JavaScript Program to Find the Most Frequent Element in an Array

In this article, we will demonstrate different methods to find the most frequent element in an array in JavaScript. We will be given an array with multiple occurrences of values in that array and we have to output the maximum occurred element in that array.

Methods to Find the most frequent element in an array in JavaScript

  • Naive method using loops and sort function
  • Using JavaScript Object
  • Using JavaScript Map

Method 1: Naive method using Loops and Sort function

In this method, we will sort the given array and traverse it to find the maximum occurred element.

Example:

Javascript




arr = [
    1, 1, 3, 5, 7, 6, 8, 5, 6, 4,
    7, 6, 0, 2, 1, 6, 8, 9, 5,
];
  
arr.sort((a, b) => a - b);
//console.log(arr)
let count = 1,
    max = 0,
    el;
  
for (let i = 1; i < arr.length; ++i) {
    if (arr[i] === arr[i - 1]) {
        count++;
    } else {
        count = 1;
    }
    if (count > max) {
        max = count;
        el = arr[i];
    }
}
console.log("The most occured element is: " + el);


Output

The most occured element is: 6

Method 2: Using JavaScript Object

In this approach we will use JavaScript object to store the number and their occurences and find the element occurred most frequently.

Example:

Javascript




const arr = [
    1, 1, 3, 5, 7, 6, 8, 5, 6, 4,
    7, 6, 0, 2, 1, 6, 8, 9, 5,
];
  
obj = {};
let el,
    max = 0;
for (let i = 0; i < arr.length; i++) {
    if (!obj[arr[i]]) obj[arr[i]] = 1;
    else obj[arr[i]]++;
}
  
for (const i in obj) {
    if (max < obj[i]) {
        max = obj[i];
        el = i;
    }
}
  
console.log("The most occured element is: " + el);


Output

The most occured element is: 6

Method 3: Using JavaScript Map and forEach method

In this method, we will use JavaScript Map to map the values with number of occurrences and print the maximum occurred element

Example:

Javascript




const arr = [
    3, 5, 7, 6, 8, 5, 6, 4, 7, 1, 
    6, 0, 2, 1, 6, 8, 9, 5, 1,
];
  
let m = new Map();
  
for (const i in arr) {
    if (!m.get(arr[i])) m.set(arr[i], 1);
    else {
        m.set(arr[i], m.get(arr[i]) + 1);
    }
}
let max = 0;
let el;
m.forEach((val, key, map) => {
    if (max < val) {
        max = val;
        el = key;
    }
});
console.log("The most occured element is: " + el);


Output

The most occured element is: 6
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments