How to find the most repeated item of an array in javascript

Posted By : Vinay Tiwari | 24-Dec-2017

Here in this code, we have taken an array of finite elements. We want to show the maximum repeated number or characters. So, we have to take a counter variable which is initialy zero. It will increment by one whenever the repeated element is found. First, we have to compare the arr[0] element of index zero as array always starts from zero indexes. we have to compare all the element of array one by one and the result will be shown after compering the last element. The 'm' will again set to zero after comparing the first element and the item with its number or repetation will be printed at the end. This process will be repeated until all the elements of array are compared.

 

Now will define the code structure

 



var arr = [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 < arr.length; i++) {
  for (var j = i; j < arr.length; j++) {
    if (arr[i] == arr[j]) m++;
    if (mf < m) {
      mf = m;
      item = arr[i];
    }
  }

m = 0;
}

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

 

Declaration

 

  • 'arr' here is the array of finite number. 
  • 'mf' is the default maximum frequency.
  • 'm' is used for incrementing the element and initially set to zero.
  • 'item' is used for assigning the element.

Here we would select the 1st element of the given array and compare it with every element from there onwards.

Then the counter 'm' would increament every time the same elements occur, which means the frequency of that element.

 

Also a variable 'mf' is kept inorder to keep track of maximum frequency.Then the elements frequency will be compared with maximum frequency and item would be updated and 'mf' as per current element's frequency.

 

Thanks

 

About Author

Author Image
Vinay Tiwari

Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.

Request for Proposal

Name is required

Comment is required

Sending message..