Home >Web Front-end >JS Tutorial >How to Find the Most Frequent Element in an Array?

How to Find the Most Frequent Element in an Array?

Barbara Streisand
Barbara StreisandOriginal
2024-11-15 15:47:02493browse

How to Find the Most Frequent Element in an Array?

Determining the Element with the Highest Occurrence in an Array

Determining the most frequently occurring element (mode) in an array is a common programming task. For a given array, we need to find the element that appears the most times.

To elegantly solve this problem, one approach is to utilize a mode map. The mode map serves as a lookup table that associates each unique element in the array with its respective frequency of occurrence. By iterating through the array, we maintain the current highest occurrence and the corresponding element.

The following JavaScript solution implements this approach:

function mode(array) {
  if (array.length === 0) {
    return null;
  }

  let modeMap = {};
  let maxEl = array[0];
  let maxCount = 1;

  for (let i = 0; i < array.length; i++) {
    let el = array[i];
    if (modeMap[el] == null) {
      modeMap[el] = 1;
    } else {
      modeMap[el]++;
    }

    if (modeMap[el] > maxCount) {
      maxEl = el;
      maxCount = modeMap[el];
    }
  }

  return maxEl;
}

In this solution, we initialize the mode map as an empty object. We then iterate through the array elements, incrementing their respective counts in the mode map. We continuously update the highest occurrence and the corresponding element by tracking the element that appears the most times. Finally, we return the element with the highest occurrence as the mode.

The above is the detailed content of How to Find the Most Frequent Element in an Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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