If a user enters 5 numbers, lets say… 4, 4, 7, 7, 4. 4 occurred 3 (most number of) times. So the output should be 4.
How can I do this using JavaScript? Would much appreciate your help.
Thanks!
I’ve tried this so far. It works, but it’s too long, looking for something short and simple way.
P.S. This is not my homework!
var n = parseInt(prompt("How many numbers do you like to enter?", ""));
var num = new Array();
for (i = 1; i <= n; i++) {
num[i] = parseInt(prompt("Enter a number", ""));
document.write("Entered numbers are: " + num[i] + "<br/>");
}
var total = new Array();
for (i = 1; i <= n; i++) {
var count = 1;
for (j = i + 1; j <= n; j++) {
if (num[i] == num[j]) {
count++;
}
total[i] = count;
}
}
var most = 0;
for (i = 0; i < n; i++) {
if (most < total[i]) {
most = total[i];
}
var val = i;
}
document.write("<br/>" + num[val] + " is occurred " + most + " times");
Create an array
awith a lot of numbers, using array literals:Create a plain object
o, using object literals.Loop through array
ausing afor(;;)-loop and increment the counter. The counter is stored in a hashmap on objecto.(o[a[i]] || 0)is needed for the first occurrence of the key: When it’s not found, the value0is used instead ofundefined. See also Short-circuit evaluation: Logical OR.Then you have an object
owhich looks like:Then loop through
ousing afor(.. in ..)-loop and find max times presented.At the bottom of the loop, the conditional ternary
.. ? .. : ..operator is used:After this loop
mis equal to:And the maximum value can be captured using:
witch gives you:
DEMO
http://jsbin.com/utiqey/