xxxxxxxxxx
function findMostFrequent(arr) {
var repsCount = {};
for (i = 0; i < arr.length; i++) {
if (!repsCount[arr[i]]) {
repsCount[arr[i]] = 1;
} else {
repsCount[arr[i]] = repsCount[arr[i]] + 1;
}
}
var occursMore = [];
for (var key in repsCount) {
if (repsCount[key] > occursMore) {
occursMore.push(key);
}
}
return occursMore;
}
get most frequent element in array javascript
xxxxxxxxxx
var mostFrequentEven = function(nums) {
newMap = new Map();
const frequency = nums => {
nums.forEach((item) => {
if(newMap.has(item)) newMap.set(item, newMap.get(item) + 1)
else newMap.set(item, 1)
})
const sortedArr = Array.from(newMap.keys()).sort((a, b) => {
if (newMap.get(a) !== newMap.get(b)) {
return newMap.get(b) - newMap.get(a);
} else {
return a - b;
}
});
return sortedArr.length !== 0 ? sortedArr[0] : -1
}
return frequency(nums)
};
xxxxxxxxxx
function findMostFrequentElement(inputArray) {
if (inputArray.length === 0) {
return null; // Return null for an empty array
}
const frequencyCount = {};
let mostFrequentElement;
let maxFrequency = 0;
for (const num of inputArray) {
frequencyCount[num] = (frequencyCount[num] || 0) + 1;
if (frequencyCount[num] > maxFrequency) {
maxFrequency = frequencyCount[num];
mostFrequentElement = num;
}
}
return mostFrequentElement;
}
// Test the program
const inputArray = [3, 5, 2, 5, 3, 3, 1, 4, 5];
const mostFrequent = findMostFrequentElement(inputArray);
console.log(mostFrequent); // Output: 3