Seeking help with a JavaScript coding challenge that I'm stuck on, here is the question:
Create a function that takes an array of integers and returns an element from that array.
The function should calculate the frequency of each element (how many times it appears in the array) and ideally return the element with the second-lowest frequency. If that's not possible, it should return the element with the lowest frequency.
If there are multiple elements that meet the criteria, the second smallest one (based on value) should be returned.
Examples:
secondLowest( [4, 3, 1, 1, 2] ) === 1
secondLowest( [4, 3, 1, 1, 2, 2] ) === 2
secondLowest( [4, 3, 1, 2] ) === 2
Here is what I have so far, but I'm unsure how to proceed:
function mode(array) {
if (array.length == 0) return null;
let modeMap = {};
let maxEl = array[0],
maxCount = 1;
for (let 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];
}
}
return maxEl;
}