Home > Web Front-end > JS Tutorial > How to Find the Most Occurring Element in a JavaScript Array?

How to Find the Most Occurring Element in a JavaScript Array?

Patricia Arquette
Release: 2024-11-15 16:09:02
Original
296 people have browsed it

How to Find the Most Occurring Element in a JavaScript Array?

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']
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template