Top JS Array Methods Interview Questions to Know
Prepare for JavaScript interviews with the most common array method questions. Covers map, filter, reduce, find, sort, flat, destructuring, spread, and tricky edge cases with detailed answers and code solutions.
Array methods are among the most tested topics in JavaScript interviews. Interviewers use them to evaluate your understanding of arrays, functional programming concepts, and problem-solving ability. Whether you are preparing for a junior or mid-level position, knowing how map, filter, reduce, and sort work under the hood will set you apart.
This guide covers the most frequently asked array method interview questions with detailed explanations and complete code solutions.
Question 1: What Does map() Return?
Question: What is the difference between map() and forEach()? When would you use each one?
Answer:
const numbers = [1, 2, 3, 4, 5];
// map: returns a NEW array with transformed values
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] -- unchanged
// forEach: returns undefined, used for side effects
const results = numbers.forEach((n) => console.log(n));
console.log(results); // undefined| Feature | map() | forEach() |
|---|---|---|
| Returns | New array | undefined |
| Chainable | Yes (.map().filter()) | No |
| Use case | Data transformation | Side effects (logging, DOM updates) |
| Immutability | Creates new array | Does not create new array |
For a detailed comparison, see map vs forEach.
Key point for interviewers: Always say "map returns a new array of the same length" and "forEach is for side effects when you do not need a return value."
Question 2: Remove Duplicates from an Array
Question: Write a function that removes duplicate values from an array.
Answer:
// Method 1: Set (most common expected answer)
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 3, 4])); // [1, 2, 3, 4]
console.log(removeDuplicates(["a", "b", "a", "c"])); // ["a", "b", "c"]
// Method 2: filter + indexOf (shows deeper understanding)
function removeDuplicatesFilter(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
// Method 3: reduce (shows functional programming knowledge)
function removeDuplicatesReduce(arr) {
return arr.reduce((unique, item) => {
return unique.includes(item) ? unique : [...unique, item];
}, []);
}Follow-up: "How would you remove duplicates from an array of objects?" Use a Map keyed by the unique property.
Question 3: Flatten a Nested Array
Question: Flatten [1, [2, [3, [4]], 5]] into [1, 2, 3, 4, 5].
Answer:
// Method 1: flat(Infinity)
const nested = [1, [2, [3, [4]], 5]];
const flat = nested.flat(Infinity);
console.log(flat); // [1, 2, 3, 4, 5]
// Method 2: Recursive function (what interviewers want to see)
function flattenDeep(arr) {
return arr.reduce((result, item) => {
if (Array.isArray(item)) {
return [...result, ...flattenDeep(item)];
}
return [...result, item];
}, []);
}
console.log(flattenDeep([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]
// Method 3: Iterative with stack (no recursion)
function flattenIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length > 0) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.unshift(next);
}
}
return result;
}For more on the built-in method, see the flat() method guide.
Question 4: Find the Maximum Value
Question: Find the largest number in an array without using Math.max.
Answer:
const scores = [72, 95, 83, 100, 67, 88];
// Method 1: reduce
const max = scores.reduce((highest, current) => {
return current > highest ? current : highest;
}, -Infinity);
console.log(max); // 100
// Method 2: sort (less efficient but valid)
const maxSort = [...scores].sort((a, b) => b - a)[0];
console.log(maxSort); // 100
// Method 3: Math.max with spread (the easy way)
const maxSpread = Math.max(...scores);
console.log(maxSpread); // 100Why -Infinity as initial value? It guarantees the first element always becomes the initial highest, even if all numbers are negative.
Question 5: Implement Array.map() from Scratch
Question: Write your own version of Array.prototype.map.
Answer:
Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
// Test it
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.myMap((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// With index parameter
const indexed = numbers.myMap((n, i) => `${i}: ${n}`);
console.log(indexed); // ["0: 1", "1: 2", "2: 3", "3: 4", "4: 5"]Key points: The callback receives three arguments (element, index, array), and map always returns a new array of the same length.
Question 6: Group Array Elements by Property
Question: Group an array of objects by a given property.
Answer:
const people = [
{ name: "Alice", department: "Engineering" },
{ name: "Bob", department: "Marketing" },
{ name: "Charlie", department: "Engineering" },
{ name: "Diana", department: "Marketing" },
{ name: "Eve", department: "Design" }
];
function groupBy(arr, key) {
return arr.reduce((groups, item) => {
const groupKey = item[key];
if (!groups[groupKey]) {
groups[groupKey] = [];
}
groups[groupKey].push(item);
return groups;
}, {});
}
const grouped = groupBy(people, "department");
console.log(grouped);
// {
// Engineering: [{name: "Alice",...}, {name: "Charlie",...}],
// Marketing: [{name: "Bob",...}, {name: "Diana",...}],
// Design: [{name: "Eve",...}]
// }
// Modern alternative: Object.groupBy (ES2024)
// const grouped = Object.groupBy(people, (p) => p.department);Question 7: Sum All Values Using reduce()
Question: Calculate the total price of all items in a shopping cart.
Answer:
const cart = [
{ item: "Laptop", price: 999, quantity: 1 },
{ item: "Mouse", price: 29, quantity: 2 },
{ item: "Keyboard", price: 79, quantity: 1 },
{ item: "Monitor", price: 349, quantity: 2 }
];
const total = cart.reduce((sum, product) => {
return sum + product.price * product.quantity;
}, 0);
console.log(total); // 1834
// Breakdown:
// Laptop: 999 * 1 = 999
// Mouse: 29 * 2 = 58
// Keyboard: 79 * 1 = 79
// Monitor: 349 * 2 = 698
// Total: 999 + 58 + 79 + 698 = 1834Interviewer tip: Always double-check arithmetic in interviews. Show the reduce accumulator step by step.
Question 8: Sort an Array of Objects
Question: Sort users by age (ascending), then by name (alphabetically) for equal ages.
Answer:
const users = [
{ name: "Charlie", age: 30 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Diana", age: 25 },
{ name: "Eve", age: 28 }
];
const sorted = [...users].sort((a, b) => {
// Primary: sort by age ascending
if (a.age !== b.age) {
return a.age - b.age;
}
// Secondary: sort by name alphabetically
return a.name.localeCompare(b.name);
});
console.log(sorted);
// [
// { name: "Alice", age: 25 },
// { name: "Diana", age: 25 },
// { name: "Eve", age: 28 },
// { name: "Bob", age: 30 },
// { name: "Charlie", age: 30 }
// ]Remember that sort mutates the original array. Always create a copy with spread or .slice() before sorting if you need to preserve the original.
For numeric sorting pitfalls, see sorting numbers correctly.
Question 9: Chain Methods Together
Question: From a list of transactions, find the total amount spent by a specific user on completed orders.
Answer:
const transactions = [
{ userId: 1, amount: 50, status: "completed" },
{ userId: 2, amount: 30, status: "pending" },
{ userId: 1, amount: 75, status: "completed" },
{ userId: 1, amount: 20, status: "cancelled" },
{ userId: 2, amount: 100, status: "completed" },
{ userId: 1, amount: 45, status: "completed" }
];
const userOneTotal = transactions
.filter((t) => t.userId === 1)
.filter((t) => t.status === "completed")
.reduce((sum, t) => sum + t.amount, 0);
console.log(userOneTotal); // 170 (50 + 75 + 45)
// Single-pass alternative (more efficient)
const userOneTotalSingle = transactions.reduce((sum, t) => {
if (t.userId === 1 && t.status === "completed") {
return sum + t.amount;
}
return sum;
}, 0);Discussion point: Method chaining is more readable but creates intermediate arrays. A single reduce is more efficient for large datasets but harder to read. Know both approaches.
Question 10: Implement a Chunk Function
Question: Split an array into groups of a specified size.
Answer:
function chunk(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
// [[1, 2, 3], [4, 5, 6], [7]]
console.log(chunk([1, 2, 3, 4], 2));
// [[1, 2], [3, 4]]
console.log(chunk([1, 2, 3], 5));
// [[1, 2, 3]]
// Reduce version
function chunkReduce(arr, size) {
return arr.reduce((chunks, item, index) => {
if (index % size === 0) {
chunks.push([item]);
} else {
chunks[chunks.length - 1].push(item);
}
return chunks;
}, []);
}Quick Reference: Methods That Mutate vs. Methods That Don't
| Mutates Original | Creates New Array/Value |
|---|---|
push(), pop() | map() |
shift(), unshift() | filter() |
splice() | reduce() |
sort() | slice() |
reverse() | concat() |
fill() | flat(), flatMap() |
Rune AI
Key Insights
- Know the return values: map returns a new array, filter returns a subset, reduce returns a single value, forEach returns undefined.
- Mutation awareness is critical: sort, splice, push, and pop mutate; map, filter, reduce, and slice do not.
- Implement from scratch: being able to write map and reduce manually proves deep understanding of iterators and callbacks.
- Choose the right tool: use map for transformations, filter for selection, reduce for aggregation, and find for single lookups.
- Practice method chaining: real interview problems combine multiple methods; explain the data flow at each step.
Frequently Asked Questions
Which array methods are asked most in JavaScript interviews?
Should I use reduce for everything?
What is the difference between find and filter?
How do I explain method chaining in an interview?
Does sort() mutate the original array?
Conclusion
JavaScript array method questions test both your knowledge of the standard library and your ability to think functionally. Master the core methods (map, filter, reduce, find, sort, flat) and know when each is appropriate. Practice implementing map and reduce from scratch so you understand the underlying mechanics. In interviews, always clarify whether mutation is acceptable, discuss performance trade-offs between method chaining and single-pass reduce, and demonstrate awareness of edge cases like empty arrays and undefined values.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.