Home > Article > Web Front-end > How to Find the Most Frequent Element in an Array in JavaScript?
Identifying the Most Occurring Element in an Array
Determining the element with the highest occurrence, also known as the mode, in a given array poses an intriguing programming challenge. Let's delve into a concise yet efficient approach that calculates the mode in a JavaScript array.
Solution Overview
The objective is to construct a mapping of elements to their respective occurrences in the array. Subsequently, we iterate through this mapping and identify the element with the maximum occurrence, which represents the mode. This approach ensures a time complexity of O(n), where n is the length of the array.
Implementation
The code snippet below embodies this approach:
function mode(array) { if (array.length === 0) return null; const modeMap = {}; let maxEl = array[0]; let maxCount = 1; for (let i = 0; i < array.length; i++) { const el = array[i]; if (modeMap[el] === undefined) modeMap[el] = 1; else modeMap[el]++; if (modeMap[el] > maxCount) { maxEl = el; maxCount = modeMap[el]; } } return maxEl; }
Usage
To utilize this function, simply provide an array containing the elements whose mode you wish to determine. For instance, consider the following:
const array = ['pear', 'apple', 'orange', 'apple']; const result = mode(array); // 'apple'
In this example, the mode of the array is 'apple' as it appears twice, which is the highest frequency among the elements.
The above is the detailed content of How to Find the Most Frequent Element in an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!