Home > Web Front-end > JS Tutorial > body text

How to Find the Most Frequent Element in an Array in JavaScript?

DDD
Release: 2024-11-21 10:40:11
Original
359 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template