Skip to content

Instantly share code, notes, and snippets.

@davidcalhoun
Last active December 16, 2017 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidcalhoun/274c8e4fdeb6972c0a494f9cea673ddf to your computer and use it in GitHub Desktop.
Save davidcalhoun/274c8e4fdeb6972c0a494f9cea673ddf to your computer and use it in GitHub Desktop.
Find the most frequent occurrences in a list with JavaScript
// List of items to find occurrences in.
const list = ['Tom', 'Fluffy', 'Tom', 'Bella', 'Chloe', 'Tom', 'Chloe'];
// Creates a Map (hash) of occurrence numbers.
const counts = list.reduce((accumulator, val) => {
// Initialize entry if needed.
if (!accumulator.has(val)) accumulator.set(val, 0);
// Increment value.
accumulator.set(val, accumulator.get(val) + 1);
return accumulator;
}, new Map());
// -> Map(4) {"Tom" => 3, "Fluffy" => 1, "Bella" => 1, "Chloe" => 2}
// Convert the counts Map to an Array of Arrays, so we can sort.
const countsArr = [...counts];
// -> [["Tom", 3], ["Fluffy", 1], ["Bella", 1], ["Chloe", 2]]
// Sort descending and grab the first value.
countsArr.sort((a, b) => b[1] - a[1])[0];
// -> ["Tom", 3]
// ===========================
// Pretty unreadable "one liner" version
[...list.reduce((accumulator, val) => {
if (!accumulator.has(val)) accumulator.set(val, 0);
return accumulator.set(val, accumulator.get(val) + 1);
}, new Map())].sort((a, b) => b[1] - a[1])[0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment