user5723270 user5723270 - 4 years ago 113
Javascript Question

Counting numbers in an random array

So I'm trying to find how many of each number from zero to ten is generated in a random array.
I created a random array list

i=0;
var ranList=[];
while (i<20){
i++;
ranList.push(Math.floor(10*Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));

/*Then I made a function to count /elements from this array
*/


function ctnumber(array,elem){
var ct=0;
var j =0;
while(j<array.length)
{
j++;
if(array[j]==elem){
ct+=1;}
}
}
return ct;
}
alert(ctnumber(ranList,5));


The second function doesn't execute, any idea why?

Thank you!

Answer Source

First you should avoid using the name array for you variable: http://www.w3schools.com/js/js_reserved.asp

Your brackets are also wrong. Change your function to this and it should work:

function ctnumber(arr,elem){
      var ct=0;
      var j =0;
        while(j<arr.length)
        {
        j++;
          if(arr[j]==elem){
          ct+=1;}
         }
      return ct;
      }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download