JavaScriptEasy
Count frequency of elements in array
Count frequencies in one pass with a Map (value → count); it is O(n), handles any value type including NaN and objects, and preserves first-seen order, after which you can sort or filter the counts as needed.
Why a Map rather than an object
- Object keys are always strings:
1and"1"collide, and keys like"constructor"or"__proto__"can clash with inherited properties. - A
Mapkeeps types distinct, has asize, and iterates in insertion order. For simple string data an object (orObject.create(null)) is fine, andObject.groupBycan count too.
Common follow-ups
- Most frequent element (the mode): track the max while counting, or sort the entries.
- Top k frequent elements: sort entries by count (O(n log n)), or use bucket sort by count for O(n).
- Characters in a string:
for (const ch of str)iterates by code point, so emoji are counted correctly. - Words in text: normalise case and split on non-letters (
/\P{L}+/u) first. - First non-repeating element: count, then scan again for the first with count 1.
- Are two strings anagrams? Compare their character counts.
Complexity
O(n) time and O(k) space for k distinct values; sorting the result adds O(k log k).
Code example
js
1function countFrequency(items) {2 const counts = new Map();3 for (const item of items) counts.set(item, (counts.get(item) ?? 0) + 1);4 return counts;5}67const votes = ["js", "ts", "js", "go", "ts", "js", 1, "1", NaN, NaN];8console.log(countFrequency(votes)); // Map { "js" => 3, "ts" => 2, "go" => 1, 1 => 1, "1" => 1, NaN => 2 }910// Most frequent (mode) and top-k11const entries = [...countFrequency(["a", "b", "a", "c", "b", "a"])];12const sorted = entries.sort((x, y) => y[1] - x[1]);13console.log("mode:", sorted[0][0], "| top 2:", sorted.slice(0, 2).map(([v]) => v)); // mode: a | top 2: ["a", "b"]1415// Characters (emoji-safe) and words16console.log(Object.fromEntries(countFrequency("hello😀😀"))); // { h: 1, e: 1, l: 2, o: 1, "😀": 2 }17const text = "The cat and the hat. THE end!";18const words = text.toLowerCase().split(/\P{L}+/u).filter(Boolean);19console.log(Object.fromEntries(countFrequency(words))); // { the: 3, cat: 1, and: 1, hat: 1, end: 1 }2021// First non-repeating character22const firstUnique = (s) => {23 const counts = countFrequency(s);24 return [...s].find((ch) => counts.get(ch) === 1) ?? null;25};26console.log(firstUnique("swiss"), firstUnique("aabb")); // w null2728// Anagram check using counts29const isAnagram = (a, b) => {30 if (a.length !== b.length) return false;31 const counts = countFrequency(a);32 for (const ch of b) {33 if (!counts.get(ch)) return false;34 counts.set(ch, counts.get(ch) - 1);35 }36 return true;37};38console.log(isAnagram("listen", "silent"), isAnagram("rat", "car")); // true false
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.