Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

JavaScript Array Methods Interview Questions: map, filter, reduce and More

12 JavaScript array interview questions with answers: map vs forEach, filter, reduce, find vs filter, some and every, sort pitfalls, mutating vs non-mutating methods, flat and flatMap, grouping, slice vs splice and polyfills for map and reduce.

Sumit KumarUpdated Oct 12, 20266 min readJavaScript
JavaScript Array Methods Interview Questions: map, filter, reduce and More

Arrays are the data structure you touch most in frontend code, so interviewers test array methods in both theory and live coding. This post covers 12 questions, from map vs forEach to writing reduce yourself, with answers and runnable examples.

Chaining JavaScript array methods: filter keeps even numbers from 1 to 6, map multiplies them by 10, and reduce sums them to 120

Core iteration methods#

Q1. What is the difference between map and forEach?#

mapforEach
ReturnsA new array of the same lengthundefined
ChainableYesNo
PurposeTransform each itemRun a side effect for each item
Stop earlyNo (neither can break)No
JavaScript
const prices = [100, 250, 400];
const withTax = prices.map((p) => p * 1.18);     // [118, 295, 472]
prices.forEach((p) => console.log(p));            // logs, returns undefined

Using map only for side effects (and ignoring the result) is a code smell; use forEach or for...of. To stop early, use for...of with break, or some/find.

Q2. Explain reduce with a few practical examples.#

Answer: reduce(callback, initialValue) walks the array and carries an accumulator from one step to the next, folding the array into a single value of any type.

JavaScript
const cart = [
  { name: "Pen", price: 20, qty: 3 },
  { name: "Book", price: 300, qty: 1 },
];

// Sum
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);   // 360

// Array → object (index by key)
const byName = cart.reduce((acc, item) => ({ ...acc, [item.name]: item }), {});

// Count occurrences
const counts = ["a", "b", "a"].reduce((acc, ch) => {
  acc[ch] = (acc[ch] ?? 0) + 1;
  return acc;
}, {});   // { a: 2, b: 1 }
Always pass an initial value

Without one, reduce uses the first element as the accumulator and throws a TypeError on an empty array.

Q3. What is the difference between find, findIndex, filter, some and every?#

MethodReturnsStops early?
findFirst matching item or undefinedYes
findIndexIndex of first match or -1Yes
findLast / findLastIndexSame, searching from the endYes
filterNew array of all matchesNo
sometrue if any item matchesYes, at the first true
everytrue if all items match (true for empty arrays)Yes, at the first false
JavaScript
const users = [{ id: 1, active: true }, { id: 2, active: false }];
users.find((u) => u.id === 2);        // { id: 2, active: false }
users.filter((u) => u.active);        // [{ id: 1, active: true }]
users.some((u) => !u.active);         // true
users.every((u) => u.id > 0);         // true
[1, 2, 3].includes(2);                // true: simple value check

Sorting and mutation#

Q4. Why does [10, 1, 5, 100].sort() return [1, 10, 100, 5]?#

Answer: Without a comparator, sort converts items to strings and sorts them in UTF-16 order, so "100" comes before "5". Always pass a comparator for numbers. Since ES2019 sort is guaranteed to be stable.

JavaScript
[10, 1, 5, 100].sort((a, b) => a - b);   // [1, 5, 10, 100]
[10, 1, 5, 100].sort((a, b) => b - a);   // [100, 10, 5, 1]

// Sort objects by multiple keys
employees.sort((a, b) =>
  a.dept.localeCompare(b.dept) || b.salary - a.salary
);

Q5. Which array methods mutate the original array?#

MutatingNon-mutating alternative
push, pop, shift, unshift[...arr, x], arr.slice(0, -1)
sorttoSorted (ES2023)
reversetoReversed
splicetoSpliced
arr[i] = xarr.with(i, x)
fill, copyWithinmap to a new array

This matters in React and Redux: state updates must produce new arrays so that reference checks detect the change.

JavaScript
const sorted = todos.toSorted((a, b) => a.priority - b.priority);  // original untouched
setTodos((prev) => prev.map((t) => t.id === id ? { ...t, done: true } : t));

Q6. What is the difference between slice and splice?#

JavaScript
const letters = ["a", "b", "c", "d", "e"];

letters.slice(1, 3);        // ["b", "c"]  (end not included), original unchanged
letters.slice(-2);          // ["d", "e"]

const removed = letters.splice(1, 2, "X");  // remove 2 items at index 1, insert "X"
removed;                    // ["b", "c"]
letters;                    // ["a", "X", "d", "e"]  (mutated)

Answer: slice(start, end) returns a shallow copy of a portion and never mutates. splice(start, deleteCount, ...items) removes and/or inserts in place and returns the removed items.

Transforming data#

Q7. How do you flatten a nested array?#

JavaScript
const nested = [1, [2, [3, [4]]]];
nested.flat();              // [1, 2, [3, [4]]]  (depth 1 by default)
nested.flat(Infinity);      // [1, 2, 3, 4]

// flatMap = map + flat(1)
const sentences = ["hello world", "hi there"];
sentences.flatMap((s) => s.split(" "));   // ["hello", "world", "hi", "there"]

// Recursive flatten (a common "no built-ins" interview ask)
function flatten(arr) {
  return arr.reduce(
    (acc, x) => (Array.isArray(x) ? acc.concat(flatten(x)) : acc.concat(x)),
    []
  );
}

Q8. Group an array of objects by a property.#

JavaScript
const orders = [
  { id: 1, status: "paid" },
  { id: 2, status: "pending" },
  { id: 3, status: "paid" },
];

// ES2024
Object.groupBy(orders, (o) => o.status);
// { paid: [{id:1}, {id:3}], pending: [{id:2}] }

// With reduce (works everywhere)
const grouped = orders.reduce((acc, o) => {
  (acc[o.status] ??= []).push(o);
  return acc;
}, {});

Q9. Find the most frequent element and the second largest number.#

JavaScript
function mostFrequent(arr) {
  const freq = new Map();
  let best, bestCount = 0;
  for (const x of arr) {
    const c = (freq.get(x) ?? 0) + 1;
    freq.set(x, c);
    if (c > bestCount) { best = x; bestCount = c; }
  }
  return best;
}
mostFrequent([3, 1, 3, 2, 1, 3]);    // 3

function secondLargest(arr) {
  let first = -Infinity, second = -Infinity;
  for (const n of arr) {
    if (n > first) { second = first; first = n; }
    else if (n > second && n !== first) second = n;
  }
  return second === -Infinity ? null : second;
}
secondLargest([5, 9, 9, 7]);         // 7  (single pass, O(n))

Polyfills and performance#

Q10. Write a polyfill for Array.prototype.map.#

JavaScript
Array.prototype.myMap = function (callback, thisArg) {
  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }
  const result = new Array(this.length);
  for (let i = 0; i < this.length; i++) {
    if (i in this) {                                   // skip holes like the native map
      result[i] = callback.call(thisArg, this[i], i, this);
    }
  }
  return result;
};

[1, 2, 3].myMap((n) => n * 2);   // [2, 4, 6]

Q11. Write a polyfill for Array.prototype.reduce.#

JavaScript
Array.prototype.myReduce = function (callback, ...init) {
  let i = 0;
  let acc;
  if (init.length) {
    acc = init[0];
  } else {
    while (i < this.length && !(i in this)) i++;      // first existing element
    if (i >= this.length) throw new TypeError("Reduce of empty array with no initial value");
    acc = this[i++];
  }
  for (; i < this.length; i++) {
    if (i in this) acc = callback(acc, this[i], i, this);
  }
  return acc;
};

[1, 2, 3].myReduce((a, b) => a + b);      // 6
[].myReduce((a, b) => a + b, 0);          // 0

Note ...init is used so an explicit undefined initial value is still treated as provided.

Q12. Is chaining map, filter and reduce slow?#

Answer: Each method loops once and creates an intermediate array, so arr.filter().map().reduce() walks the data three times. For typical UI data (hundreds or thousands of items) this is negligible and readability wins. For very large arrays or hot paths, combine the steps into one reduce or a plain for loop, or use lazy iterators.

JavaScript
// Three passes, very readable
const total = items.filter((i) => i.inStock).map((i) => i.price).reduce((a, b) => a + b, 0);

// One pass
let total2 = 0;
for (const i of items) if (i.inStock) total2 += i.price;

// ES2025 iterator helpers: lazy, no intermediate arrays
const firstTwo = items.values().filter((i) => i.inStock).take(2).toArray();

Quick revision#

NeedMethod
Transform every itemmap
Keep some itemsfilter
Combine into one valuereduce
First matchfind
Any / all matchsome / every
Sort without mutatingtoSorted
Flattenflat, flatMap
GroupObject.groupBy

More hands-on practice: JavaScript polyfills interview questions and the sliding window technique.

Key takeaways#

  • map returns a new array; forEach returns nothing and is for side effects.
  • Always give reduce an initial value, and give sort a comparator for numbers.
  • Know which methods mutate (sort, reverse, splice, push) and their immutable versions (toSorted, toReversed, toSpliced, with).
  • Use flat, flatMap and Object.groupBy for common data reshaping.
  • Be ready to write map, filter and reduce polyfills, including the hole and empty-array edge cases.