Interview Q&A · JavaScript · 12 questions in this topic
Arrays & Array Methods — JavaScript Interview Q&A
The iteration toolkit — map/filter/reduce, mutation vs copy, sorting and flattening. Part of Arrays, Strings & Collections · 204 questions in the JavaScript bank.
How do map, filter and forEach differ?
Answer
map transforms each element, returning a new array (pure pipeline step). filter keeps matching elements in a new array. forEach runs side effects, returning undefined — not chainable, not awaitable per-element.
Transform → map, select → filter, effects → forEach (or for...of).
Example
const nums = [1, 2, 3, 4]; nums.filter((n) => n % 2 === 0).map((n) => n * 10); // [20, 40] // forEach returns undefined — never assign it
How does `reduce` work (and when is it overkill)?
Answer
reduce folds elements into one value via (accumulator, current) plus initial value — sums, groups, lookups, pipelines. Always pass the initial value (empty-array safety, type clarity). Overkill for map/filter-shaped jobs — readability loses to one-liner cleverness.
Initial-value-always is the safety rule.
Example
const byDept = users.reduce((m, u) => { (m[u.dept] ||= []).push(u); return m; }, {}); // group-by in one pass
Which array methods mutate (and what are the immutable alternatives)?
Answer
Mutating: push/pop/shift/unshift/splice/sort/reverse/fill/copyWithin. Copying: map/filter/slice/concat/toSorted/toSpliced/toReversed/with (ES2023). React/Redux-style state demands copies — mutate a draft or spread new references.
ES2023 non-mutating quartet (toSorted/toSpliced/toReversed/with) ends the copy-then-mutate dance.
Key points
- 1Mutate — push/splice/sort/reverse family.
- 2Copy — map/filter/slice plus ES2023 toSorted/toSpliced.
- 3Rule — framework state wants new references.
Example
const sorted = [...a].sort(); // or ES2023: a.toSorted() const patched = a.with(1, 99); // copy with index set
💡 New-reference-renders is why immutability matters in UI code.
How does `sort` compare (and why does [10, 9, 80] sort wrong by default)?
Answer
Default sort stringifies (UTF-16) — [10, 9, 80] becomes [10, 80, 9]. Comparators (a, b) => a - b (numbers), localeCompare (strings), multi-key chains (date then name) fix it. Sort is in-place (use toSorted for copies) and stable (ES2019+).
Numeric compare plus localeCompare covers nearly everything.
Example
[10, 9, 80].sort(); // [10, 80, 9] (string order!) [10, 9, 80].sort((a, b) => a - b); // [9, 10, 80] ['b', 'a'].sort((x, y) => x.localeCompare(y));
How do `find`, `some`, `every` and `includes` differ (and short-circuit)?
Answer
find returns the first match (or undefined); some/every return booleans (any/all, short-circuiting); includes tests value presence (SameValueZero — finds NaN, unlike indexOf). some/every stop early; includes scans to match.
Existence → some/includes; universal → every; element → find.
Example
[NaN].includes(NaN); // true (SameValueZero) [NaN].indexOf(NaN); // -1 (strict === fails NaN)
💡 includes-finds-NaN is the differentiator to memorize.
How do `flat`, `flatMap` and nested-array handling work?
Answer
flat(depth) flattens nested arrays (default 1, Infinity for full). flatMap maps then flattens one level — filtering-plus-mapping in one pass (return [] to drop). Holes (sparse arrays) are skipped by most methods.
flatMap-filter-map is the single-pass idiom.
Example
const words = ['hi there', 'yo'].flatMap((s) => s.split(' ')); // ['hi', 'there', 'yo']
How do you dedupe arrays (primitives and objects)?
Answer
Primitives: [...new Set(arr)] (SameValueZero — NaN dedupes correctly). Objects: key-based Map (by id) or seen-set on serialized keys — reference equality never dedupes distinct objects.
Set for values, Map-by-key for entities.
Example
[...new Set([1, NaN, NaN, 2])]; // [1, NaN, 2] // objects: Map by u.id, keep first
💡 Set-uses-SameValueZero is why NaN dedupes.
How do `slice` vs `splice` differ?
Answer
slice(start, end) copies a range (non-mutating, negatives allowed). splice(start, deleteCount, ...items) edits in place (returns removed). Names differ by one letter; behaviors are opposites — the eternal confusion pair.
Copy → slice; edit → splice.
Example
const a = [1, 2, 3, 4]; a.slice(1, 3); // [2, 3], a unchanged // a.splice(1, 2); // removes [2,3], a mutated
How do you chunk, group and partition arrays?
Answer
Chunk: slice in steps. Group: Object.groupBy (ES2024) or reduce-to-object. Partition: reduce into [pass, fail] or two filters (two passes, simpler). groupBy returns null-prototype objects (safe keys).
Object.groupBy is the modern group-by one-liner.
Example
// ES2024: // Object.groupBy(users, (u) => u.dept) // { eng: [...], sales: [...] }
💡 groupBy-plus-null-prototype is the modern answer with its safety note.
How do you iterate arrays (for, for...of, forEach, entries)?
Answer
for...of yields values (break/continue/await-friendly). entries() yields [index, value] pairs for destructuring. forEach forbids break/await-per-element. Classic indexed for allows full control (reverse, step, early exit).
for...of default; entries for indices; forEach for side-effect sweeps.
Example
for (const [i, v] of arr.entries()) { if (v.done) break; // break works (unlike forEach) }
What are sparse arrays and holes (and why avoid them)?
Answer
Holes (new Array(3), [1,,3]) are empty slots — skipped by map/forEach (but not for...of, which yields undefined), with length counting them. They deoptimize engines and confuse iteration: prefer dense construction (fill, from, literals).
Holes-skip-inconsistently is why dense arrays are the rule.
Example
const h = [1, , 3]; h.map((x) => x * 2); // [2, empty, 6] (hole skipped!) Array.from({ length: 3 }, (_, i) => i); // dense [0,1,2]
How do typed arrays (Uint8Array etc.) differ from normal arrays?
Answer
Typed arrays are fixed-length views over ArrayBuffers — numeric-only, no holes, no methods-missing, cache-friendly, XCTransferable to workers. Normal arrays are dynamic, heterogenous, hole-capable objects. Binary protocols, canvas pixels, and WASM interop need typed arrays.
Buffers-plus-views is the binary-data architecture.
Example
const buf = new ArrayBuffer(8); const view = new Uint8Array(buf); // fixed-length numeric view
Recommended resourcesAffiliate links · may earn us a commission