As you will notice, I'm trying to analyze which value will occur the most frequent within a given array using hashmaps and objects. If you can, please try to identify the answer for each algorithm (hashmap and object).
The below example uses hashmaps to "map" various objects with each other. However, I am having two problems: 1. I can't increment occurrence properly: after occurrence variable is equal to 1, then that value remains forever hence the algorithm provides the wrong mode. 2. I don't know how to change the value of a map after the iteration is completed.
var highestFrequency = (array) => {
var occurenceStored = new Map();
let occurrence = 0;
for (var i = 0; i < array.length; i++){
var j = i + 1;
if (array[i] === array[j]){
occurrence += 1;
occurenceStored.set(array[i], occurrence)
}
}
console.log(occurenceStored);
}
highestFrequency([101, 104, 108, 108, 111, 119, 119, 119])
Instead of using a hashmap, I decided to use an object instead but I fall into the same problem. The occurrence variable is permanently equal to 1. I tried declaring the occurrence variable at different places but can't seem to find the right fix.
var highestFrequency = (array) => {
var occurenceStored = {};
let occurrence = 1;
for (var i = 0; i < array.length; i++){
var j = i + 1;
if (array[i] === array[j]){
occurenceStored[array[i]] = occurrence;
}
}
console.log(occurenceStored);
}
highestFrequency([101, 104, 108, 108, 111, 119, 119, 119, 120, 120, 120])