Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Max Max</title>
</head>
<body>
Enter elements delimited by comma and press enter:<br><br>
<input type="text" id="input">
<p id="output"></p>
<script>
var input = document.getElementById('input');
input.addEventListener('keyup', function(e) {
if(e.keyCode === 13) {
processInput(input.value);
}
});
function processInput(input) {
var array = input.split(",");
for (var i = 0; i < array.length; i++) {
array[i] = array[i].trim();
}
document.getElementById('output').innerHTML = mode(array);
}
function mode(array){
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++){
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount){
maxEl = el;
maxCount = modeMap[el];
}
}
input.value = "";
return maxEl;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.