mediumJS ES6+#104

Elementos pares (even-count elements)

Prompt

Given an array, return a new array with only elements that appear an even number of times. Preserve the original order based on first occurrence. Include each qualifying element once.

Solution

function evenOccurrences(arr) {
  const count = new Map()
  arr.forEach(x => count.set(x, (count.get(x) || 0) + 1))
  return [...new Set(arr)].filter(x => count.get(x) % 2 === 0)
}
Mentor's take

This is the frequency-map pattern — the workhorse behind duplicate counting, anagram grouping, and "find the element that appears k times" questions. One pass builds a histogram (element → count), then a second pass filters by whatever predicate the question asks. Two passes, each O(n): O(n) time, O(n) space total.

The naive version puts arr.filter(y => y === x).length (or indexOf-style counting) inside a loop — an O(n²) hidden in a one-liner that reads innocently. Interviewers plant this problem specifically to see whether you count once up front or re-scan per element.

The second trick is order preservation with deduplication: [...new Set(arr)] yields each distinct element in first-occurrence order, because Sets iterate in insertion order. Filtering that (instead of the raw array) gives you each qualifying element exactly once without a separate "seen" check.

Why Map and not {}: a plain object stringifies its keys, so count[1] and count['1'] are the same bucket, and a value like 'constructor' reads an inherited function instead of undefined(fn || 0) + 1 then produces a string, not a count. Map keys by identity and has no prototype. Reaching for {} here is the reflex; knowing the two ways it corrupts a histogram is the senior signal. (If you do want an object, Object.create(null) kills the prototype half of the problem.)

Red flag: filter + includes/indexOf inside the callback — O(n²) dressed up as idiomatic code. Also returning duplicates ([2,2] instead of [2]) by filtering the original array instead of the deduplicated one.

Say it: "I build a frequency map in one O(n) pass with a Map — object keys would coerce 1 and '1' into one bucket — then filter the Set of the array, which keeps insertion order so I get first-occurrence order and dedup for free."