Files
30-seconds-of-code/snippets/mostFrequent.md
Angelos Chalaris 8a6b73bd0c Update covers
2023-02-16 22:24:28 +02:00

763 B

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
Most frequent element in array array chalarangelo clock 2020-01-03T15:32:46+02:00 2020-09-15T16:28:04+03:00

Returns the most frequent element in an array.

  • Use Array.prototype.reduce() to map unique values to an object's keys, adding to existing keys every time the same value is encountered.
  • Use Object.entries() on the result in combination with Array.prototype.reduce() to get the most frequent value in the array.
const mostFrequent = arr =>
  Object.entries(
    arr.reduce((a, v) => {
      a[v] = a[v] ? a[v] + 1 : 1;
      return a;
    }, {})
  ).reduce((a, v) => (v[1] >= a[1] ? v : a), [null, 0])[0];
mostFrequent(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // 'a'