Frequent Number In Javascript
Solution 1:
You can use .reduce
to create an object with the numbers and the times they're listed - then simply iterate the object and find the highest value:
var ranks = array.reduce(function(totals, num) {
if (!totals[num]) totals[num] = 0;
totals[num]++;
return totals;
}, {});
//Iterate and findvar max = 0;
Object.keys(ranks).forEach(function(num) {
if (ranks[num] > max) {
max = num;
}
});
console.log(max); //4 - numberconsole.log(ranks[max]); //5 - times repeated
This doesn't take numbers with the same count into play - whichever number is iterated in the object first with the highest count will be the result - and since objects are unordered, a same count could have different results over multiple executions.
Solution 2:
I use Underscore library:
var found = _.chain(array).countBy().pairs().max(_.last);
var valueOfFrequent = found.head().value();
var numberOfFrequent = found.tail().value();
alert("number '" + valueOfFrequent + "' time of frequent: " + numberOfFrequent );
Try code in jsfiddle
Solution 3:
I think my usage of variable names will help make it more clear without too much commenting.
vararray = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
var mostUsed;
var currentNumber;
var lastNumber;
var currentCount;
var lastCount;
functionfrequentNumber(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.
Solution 4:
This is a task so I'd rather not give you the answers but a possible solution could be something like this.
- Instantiate an object with keys as the numbers in your array and the values as the number of repetitions in your array. All initial counts should be 0 and you increase it by 1 as you see each number.
ie. count['4'] = 4
in the end.
- Find the max value and save the key when you loop through the object.
This is not the most optimal but I'm sure it will do fine in your task and will be the easiest to follow. First loop does the counting. Second loop finds the maximum repeats.
Solution 5:
The easiest, and properbly most correct method, is to use the native Array.Sort method.
Inside the loop, simply count the frequency of each number, compare and return.
var arr = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
functionsortByOccurence(arr) {
return arr.sort(function(a, b) {
var A = 0,
B = 0;
if (a === b) {
return0;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] == a) {
A++;
}
if (arr[i] == b) {
B++;
}
}
return B - A;
});
}
console.log(sortByOccurence(arr));
Post a Comment for "Frequent Number In Javascript"