To find the most frequent element in an array, you can use a frequency counter to track occurrences of each element.
- Create an empty object to store element frequencies.
- Iterate through the array and count occurrences of each element by updating the object.
- Keep track of the element with the highest frequency while iterating through the object.
- Return the element with the highest frequency.
function findMostFrequentElement(arr) {
const frequency = {};
let maxFreq = 0;
let mostFrequent = null;
// Count occurrences of each element
for (const elem of arr) {
frequency[elem] = (frequency[elem] || 0) + 1;
if (frequency[elem] > maxFreq) {
maxFreq = frequency[elem];
mostFrequent = elem;
}
}
return mostFrequent;
}
// Example usage
console.log(findMostFrequentElement([1, 3, 2, 1, 4, 1, 3, 3])); // Output: 1
console.log(findMostFrequentElement(["apple", "banana", "apple", "orange", "banana", "apple"])); // Output: "apple"
This method has a time complexity of O(n) as it involves a single iteration over the array.
Tags: intermediate, JavaScript, Arrays, Algorithm, Data Structures
URL: https://www.tiktok.com/@jsmentoring/video/7458418483282316576