Skip to content

Instantly share code, notes, and snippets.

@KravMaguy
Created June 29, 2021 20:09
Show Gist options
  • Save KravMaguy/0ac5bc4b528ffe8296ecc66a0a446517 to your computer and use it in GitHub Desktop.
Save KravMaguy/0ac5bc4b528ffe8296ecc66a0a446517 to your computer and use it in GitHub Desktop.
max recurring element two ways
const globalArr = [
1, 3, 0, -10, -10, 4, 4, 4, 4, 4, 4, 4, 0, -10, 4, -10, 0, -3,
];
const loggResult = (el, count) =>
console.log(
`the most frequent value is ${el} occuring ${count} times in the array`
);
const findMaxRecurring = (array) => {
const obj = {};
//set first element of arr to be the max
let mostFrequent = array[0],
count = 1;
//iterate through array to create hash
for (let i = 0; i < array.length; i++) {
const element = array[i];
//if value falsy set to 1, else add 1
obj[element] = obj[element] == null ? 1 : (obj[element] += 1);
//if property value greater than count
if (obj[element] > count) {
//set max to be property name
mostFrequent = element;
//set count to property value
count = obj[element];
}
}
loggResult(mostFrequent, count);
};
const findMaxRecurrwReduce = (arr) => {
let count = 0;
let mostFrequent;
const countFrequency = function (arr, val) {
return arr.reduce((acc, elem) => {
return val === elem ? acc + 1 : acc;
}, 0);
};
arr.forEach((val) => {
const frequency = countFrequency(arr, val);
if (frequency > count) {
count = frequency;
mostFrequent = val;
}
});
loggResult(mostFrequent, count);
};
//findMaxRecurring(globalArr);
findMaxRecurrwReduce(globalArr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment