Finding the Most Occurring Element in an Array
Determining the element that appears most frequently (the mode) in an array can be a common programming task. One approach to tackle this issue is presented here.
Example:
Given an array like:
['pear', 'apple', 'orange', 'apple']
The objective is to identify that 'apple' appears twice, while other elements appear only once. Therefore, 'apple' is the most frequent element, or the mode.
Solution:
Below is an example function that accomplishes this task:
function mode(array) { // If the array is empty, return null if (array.length === 0) { return null; } // Create a map to store element counts var modeMap = {}; // Initialize the maximum count and element var maxCount = 1; var maxEl = array[0]; // Iterate through the array for (var i = 0; i < array.length; i++) { var el = array[i]; // Check if the element is already in the map if (modeMap[el] === undefined) { modeMap[el] = 1; } else { // Increment the count if the element is already present modeMap[el]++; } // Update the maximum element and count if the current element's count is higher if (modeMap[el] > maxCount) { maxEl = el; maxCount = modeMap[el]; } } // Return the element with the highest occurrence return maxEl; }
This function takes linear time O(n), where n is the number of elements in the array. It iterates through the array once, counting the occurrences of each element and keeping track of the most frequent one. This solution provides an elegant and efficient way to find the mode of a JavaScript array.
The above is the detailed content of How to Find the Most Occurring Element in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!