Last active
December 16, 2017 03:11
-
-
Save davidcalhoun/274c8e4fdeb6972c0a494f9cea673ddf to your computer and use it in GitHub Desktop.
Find the most frequent occurrences in a list with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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