I think my usage of variable names will help make it more clear without too much commenting.
var array = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
var mostUsed;
var currentNumber;
var lastNumber;
var currentCount;
var lastCount;
function frequentNumber(arr) {
array.sort();
var y = 1;
var tempArr = [];
for (x = 0; x < array.length; x++){
if(array[x] == array[y]){
tempArr.push(array[x]);
currentNumber = array[x];
}
else{
tempArr.push(array[x]);
currentNumber = array[x];
currentCount = tempArr.length;
//console.log(currentNumber +' occurs ' + currentCount + ' times');
tempArr =[];
if (lastCount >= currentCount){
mostUsed = lastNumber;
}
else{
mostUsed = currentNumber
}
lastCount = currentCount;
lastNumber = currentNumber;
}
y++;
}
console.log('Most Used Number is = ' +mostUsed);
}
frequentNumber(array);
What ends up happening is that after sorting your array you check if the first spot (0) matches the second spot (1) if it does you push it into a temporary array that you are just using for counting purposes. When you finally reach an item that doesn't match it still pushes it into the array but then gets the total length of that array and stores it as the currentCount and the number that is in use as the currentNumber.
Another conditional is then run on those variables. On the first iteration of all the loops there is nothing to check against since the are currentNumber is the most used number because it's compared to nothing. So that first number is tucked into what we will be using as the mostUsed variable. After that we store the current data into these other variables called lastNumber and lastCount. Then on each loop after this you compare the current count to the last count. If the lastCount is higher it stores that lastNumber as the most used and doesn't change anything. However if the currentNumber is higher it will store that as the most used number.
Does this make sense? If you don't follow the logic you should add comments at various points in the code so that you better understand it. This was a well though out and interesting coding test by your teacher. I enjoyed working through it in the cleanest simplest way.