JavaScript To Find the most frequent item of an array

If we want to filter the item from the array which is frequently used then we can follow the below Example

Here in the below example the array jjarray contain ‘a’ 5 times , so the most frequently item will be a.

Sample array: var jjarray=[3, ‘a’, ‘a’, ‘a’, 2, 3, ‘a’, 3, ‘a’, 2, 4, 9, 3];

Sample Output: a ( 5 times )

Code

// Declare and initialize the original array

var jjarray = [3, ‘a’, ‘a’, ‘a’, 2, 3, ‘a’, 3, ‘a’, 2, 4, 9, 3];

// Initialize variables to track the most frequent item, its frequency, and the current item’s frequency

var result = 1;

var m = 0;

var item;

// Iterate through the array to find the most frequent item

for (var i = 0; i < jjarray.length; i++) {

// Nested loop to compare the current item with others in the array

for (var j = i; j < jjarray.length; j++) {

// Check if the current item matches with another item in the array

if (jjarray[i] == jjarray[j])

m++;

// Update the most frequent item and its frequency if the current item’s frequency is higher

if (result < m) {

result = m;

item = jjarray[i];

}

}

// Reset the current item’s frequency for the next iteration

m = 0;

}

// Output the most frequent item and its frequency

console.log(item + ” ( “ + result + ” times ) “);

Leave a comment

Your email address will not be published. Required fields are marked *