Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Most Frequent Element

Working With Arrayshard

Course · Section 11: Working With Arrays · Lecture 156: Data Transformations: map, filter, reduce

Implement `mostFrequent(arr)` returning the element that appears most often. On a tie, return the one that reaches the highest count first.

Sample tests

Input: mostFrequent(["a","b","a","c","b","a"])
Output: "a"
Input: mostFrequent([1,2,2,3])
Output: 2

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Using >= for the best-count comparison flips the tie-break to the later element.

Learning resources

  • MDN: Array.prototype.reduce
Approach & explanation (try first)

Counting while scanning and updating the best only on a strictly higher count returns the element that first reaches the maximum frequency.

Loading...
⌘/Ctrl + Enter

Run your code to see results.