Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting the most repeating value

Status
Not open for further replies.

vasilek

Programmer
Jan 5, 2003
99
US
How to get the most repeating value. For example:

var s = "36,36,36,36,36,39,39,40,36,38,40,36";

How can I put '36' into another variable, because it is repeating more that the other values?

Thanks.
 
Code:
//Convert the string to an array.
var arrS = s.split(",");

//Take the first element as a possible answer.
var sTest = arrS[0];
var sCount = 1;

var sBest = sTest;
var bestCount = 1;


//Count the number of matches to sTest in the array.
//  And mark any matches so they won't be used again.

   //Loop through the array
      //If an element matches sTest, increment counter
      //   and mark that element as counted.
      if( arrS[i] == sTest ){
         arrS[i] = 0;
         sCount++;
      }
   
   //Compare sCount to bestCount and save the higher values.
      if( sCount > bestCount ){
         bestCount = sCount;
         sBest = sTest;
      }
   
   //Find the next element to count, if any.
      //Loop and find the first non-zero element.
   

//Repeat the process until all elements are counted.
//Remember to reset counter.
//The most frequent one will be sBest.
//Think about what you want to do about elements that appear equally often.


 
Associative arrays work well here.
Code:
  var s  = "36,36,36,36,36,39,39,40,36,38,40,36";
  var aS = s.split(",");
  var aH = new Array();
//  1. tally all unique values
  for (var j = 0; j < aS.length; j++) {
    if (!aH[aS[j]]) { aH[aS[j]] = 0; } // undefined??
    aH[aS[j]]++;
    }
//  2. find highest tally  
  var hiCount = hiValue = -1;
  for (j in aH) {
    if (aH[j] > hiCount) {
      hiCount = aH[j];
      hiValue = j;
      }
    }
  
  alert(hiValue + &quot; appears &quot; + hiCount + &quot; times&quot;);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top