Question Bank
JavaScript Array Occurrences Count: Two Approaches Quiz
Difficulty: Medium
Tally how many times each value appears in an array, two ways (reduce + dict and Map-based counter), plus two companions on Object.create(null) safety and case-insensitive string tallies.
JavaScript Array Occurrences Count: Two Approaches Quiz
Tally how many times each value appears in an array, two ways (reduce + dict and Map-based counter), plus two companions on Object.create(null) safety and case-insensitive string tallies.
886 views
27
Implement getOccurrences(arr) using Array.prototype.reduce and a plain object accumulator. Return an object keyed by value with the count as the value.
Examples
Example 1:
Input: [1, 12, 8, 5, 7, 1, 3, 5, 12, 7, 11, 8, 12, 5]
Output: { 1: 2, 3: 1, 5: 3, 7: 2, 8: 2, 11: 1, 12: 3 }
Explanation: Each value maps to how many times it appears in the input array.Implement getOccurrences(arr) again using a Map. Return the Map directly. Mention two reasons a Map is sometimes preferable to a plain object for this kind of counter.
Examples
Example 1:
Input: [1, 1, 2, "foo", "foo", true]
Output: Map { 1 => 2, 2 => 1, "foo" => 2, true => 1 }
Explanation: A Map preserves key types (the number 1 stays a number; the boolean true stays a boolean).Prototype-pollution trap: explain why const counts = {}; counts.__proto__ is risky for occurrence counters whose keys come from untrusted input. Rewrite the reduce approach to be safe.
Examples
Example 1:
Input: [`__proto__`, "x", "x"]
Output (safe): { __proto__: 1, x: 2 }
Explanation: Object.create(null) gives a prototype-less dict, so user-supplied keys cannot reach Object.prototype.Case-insensitive string tally: extend getOccurrences(arr, opts) so that when opts.caseInsensitive is true, "Foo" and "foo" are counted together. Decide whether the output key uses the FIRST seen casing or the lower-cased form.
Examples
Example 1:
Input: ["Foo", "foo", "FOO", "bar"], opts = { caseInsensitive: true }
Output: { foo: 3, bar: 1 }
Explanation: Lower-case the key on lookup and on store so all three "foo" variants land on the same bucket.