Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most frequent item of an array (not just strings)

Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.

var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var mf = 1;
var m = 0;
var item;

for (var i = 0; i < arr1.length; i++) {
  for (var j = i; j < arr1.length; j++) {
    if (arr1[i] == arr1[j]) m++;
    if (mf < m) {
      mf = m;
      item = arr1[i];
    }
  }

  m = 0;
}

alert(item + " ( " + mf + " times ) ");

I've been checking out some similar questions on stackoverflow, just can't find the answers that I want.

My questions are:

  1. I don't understand why there needs to have two for loops.

  2. Why the need for mf and m. Seems a bit confusing.

  3. Is there other way of solution on this?

like image 577
chichi Avatar asked Jul 05 '15 06:07

chichi


2 Answers

I really do not think there is a need for 2 loops in this solution. You can look at this prototyping code which uses a simple data structure called map:

var arr=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var map = {};
var mostFrequentElement = arr[0];
function findMostFrequent(){
    for(var i = 0; i<arr.length; i++){
        if(!map[arr[i]]){
            map[arr[i]]=1;
        }else{
            ++map[arr[i]];
            if(map[arr[i]]>map[mostFrequentElement]){
                mostFrequentElement = arr[i];
            }
        }
    }
    alert(mostFrequentElement);
}
like image 81
arnabkaycee Avatar answered Oct 02 '22 16:10

arnabkaycee


User want's explanation of the code:

Here they select the 1st element of the array and compare it with every element then on.

Then they increment the counter m every time the same elements occur again, frequency of that element.

Also a variable mf is kept to keep track of maximum frequency. Compare the elements frequency with maximum frequency and update item and mf as per present element's frequency.

var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3]; //array
var mf = 1; //default maximum frequency
var m = 0;  //counter
var item;  //to store item with maximum frequency
for (var i=0; i<arr1.length; i++)    //select element (current element)
{
        for (var j=i; j<arr1.length; j++)   //loop through next elements in array to compare calculate frequency of current element
        {
                if (arr1[i] == arr1[j])    //see if element occurs again in the array
                 m++;   //increment counter if it does
                if (mf<m)   //compare current items frequency with maximum frequency
                {
                  mf=m;      //if m>mf store m in mf for upcoming elements
                  item = arr1[i];   // store the current element.
                }
        }
        m=0;   // make counter 0 for next element.
}
like image 38
Ajay Narain Mathur Avatar answered Oct 02 '22 14:10

Ajay Narain Mathur