Problem 1 - Find the element which has highest occurence in the given array
Problem 1 - Find the element which has highest occurence in the given array
by Neeraj
HTML
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<div id="testcase"></div>
<script src="src/index.js"></script>
</body>
</html>
CSS
body {
font-family: sans-serif;
}
.pass {
color: white;
background-color: green;
padding: 10px;
}
.fail {
color: white;
background-color: red;
padding: 10px;
}
JavaScript
document.getElementById("app").innerHTML = `
<h1>Problem 1</h1>
<div>
Find the element which has highest occurence in the given array
</div>
`;
// Find the element which has highest occurence in the given array
function getMaxOccurrence(arr = []) {
// Write your code here
// Write your code here
// arr = [0, 9, 1, 2, 1, 1, 4, 1, 2, 1, 5];
var max = 0;
var maxElement = 0;
var countArr = {};
for(var i = 0; i < arr.length; i++) {
var count = countArr[arr[i]];
if(count === undefined) {
count = 1;
} else {
count = count + 1;
}
countArr[arr[i]] = count;
if(countArr[arr[i]] > max) {
max = countArr[arr[i]];
maxElement = arr[i];
}
}
return maxElement;
}
// Example
// getMaxOccurrence([0,9,1,2,1,1,4,1,2,1,5]) => 1
const testCases = [{
test: [0, 9, 1, 2, 1, 1, 4, 1, 2, 1, 5],
result: 1
},
{
test: ["e", "a", "b", "c", "b", "a", "c"],
result: "a"
},
{
test: ["test", "orange", "banana", "banana", "mango", "orange", "orange"],
result: "orange"
}
];
const resultString = testCases.map((tc, i) => {
const {
test,
result
} = tc;
const actual = getMaxOccurrence(test);
return `
<h3> Case ${i + 1}: </h3>
<p>Expected: ${result}: Actual: ${actual}</p>
<p>Result: ${
result === actual
? '<span class="pass">PASS<span>'
: '<span class="fail">FAIL<span>'
} </p>
`;
});
document.getElementById("testcase").innerHTML = resultString.join("");