πŸŽ“ Velnov

🟨 JavaScript · Topic 9 of 20

Array Methods β€” JavaScript Questions with Answers

30 practice questions on Array Methods, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.

2 easy Β· 17 medium Β· 11 hard Β· Part of JavaScript: The language of the web - basics to advanced, 20 topics.

Key concepts in this topic

mapImmutabilityfilterPredicatesforEachreduceAccumulatorEdge casesfindfindIndexsomeeveryChainingArrow functionsImplicit returnObject literalsCallbacksParametersparseIntGotchasReal-worldCountingGroupingflatMap

Jump to: Easy Β· Medium Β· Hard

Easy questions (2)

Q1. easy

What does map() return?

const nums = [1, 2, 3];
console.log(nums.map(n => n * 2));   // [2, 4, 6]
console.log(nums);                    // [1, 2, 3] - unchanged
  1. A A NEW array with the callback applied to every element
  2. B The same array, modified
  3. C A single value
  4. D undefined

Answer: A β€” A NEW array with the callback applied to every element

map transforms each element into a new one, always producing an array of the SAME length. The original is untouched.

mapImmutability

Q2. easy

What does filter() return?

const nums = [1, 2, 3, 4];
console.log(nums.filter(n => n % 2 === 0));   // [2, 4]
  1. A A new array with ONLY the elements whose callback returned truthy
  2. B The first matching element
  3. C true or false
  4. D The removed elements

Answer: A β€” A new array with ONLY the elements whose callback returned truthy

filter keeps elements that pass the test, so the result can be shorter (or empty). It never modifies the original.

filterPredicates

Medium questions (17)

Q3. medium

What is the key difference between map() and forEach()?

const doubled = nums.map(n => n * 2);   // use the result
nums.forEach(n => console.log(n));       // side effect only
  1. A map RETURNS a new array; forEach returns undefined and is used for side effects
  2. B They are identical
  3. C forEach is faster and returns an array
  4. D map cannot use arrow functions

Answer: A β€” map RETURNS a new array; forEach returns undefined and is used for side effects

Use map when you want a transformed array back; use forEach when you just want to DO something per element (logging, DOM updates). Using map without using its result is a code smell.

mapforEach

Q4. medium

What does reduce() do?

const total = [1, 2, 3].reduce((sum, n) => sum + n, 0);
console.log(total);   // 6
  1. A Boils an array down to a SINGLE value using an accumulator
  2. B Removes elements
  3. C Shrinks the array length
  4. D Sorts the array

Answer: A β€” Boils an array down to a SINGLE value using an accumulator

reduce((acc, item) => ..., initialValue) carries a running result across the array - sums, counts, groupings, even building objects.

reduceAccumulator

Q6. medium

What does find() return?

const users = [{id:1},{id:2}];
console.log(users.find(u => u.id === 2));       // {id: 2}
console.log(users.findIndex(u => u.id === 2));  // 1
  1. A The FIRST element matching the test, or undefined
  2. B All matching elements
  3. C The index of the match
  4. D true or false

Answer: A β€” The FIRST element matching the test, or undefined

find returns the element itself and stops at the first match. findIndex returns its position instead (or -1).

findfindIndex

Q7. medium

What is the difference between find() and filter()?

  1. A find returns ONE element (or undefined); filter returns an ARRAY of all matches
  2. B They are the same
  3. C find returns an array
  4. D filter stops at the first match

Answer: A β€” find returns ONE element (or undefined); filter returns an ARRAY of all matches

Use find when you expect a single result (it also stops early, so it is faster). filter always scans the whole array.

findfilter

Q8. medium

What do some() and every() return?

const n = [2, 4, 6];
console.log(n.some(x => x > 5));    // true
console.log(n.every(x => x % 2 === 0)); // true
console.log([].every(x => false));   // true!
  1. A Booleans - some: does AT LEAST ONE pass? every: do ALL pass?
  2. B Arrays of matches
  3. C The matching elements
  4. D Counts

Answer: A β€” Booleans - some: does AT LEAST ONE pass? every: do ALL pass?

Both short-circuit: some stops at the first true, every stops at the first false. Note every() on an EMPTY array is true (vacuous truth).

someevery

Q9. medium

What is the output? console.log([1, 2, 3].map(n => n * 2).filter(n => n > 2));

  1. A [4, 6] - map first gives [2,4,6], then filter keeps > 2
  2. B [2, 4, 6]
  3. C [4]
  4. D [2, 3]

Answer: A β€” [4, 6] - map first gives [2,4,6], then filter keeps > 2

Array methods return arrays, so they CHAIN left to right. Each step creates a new array - readable, though it iterates more than once.

Chainingmapfilter

Q12. medium

What arguments does the map callback receive?

["a","b"].map((val, i) => `${i}: ${val}`);
// ["0: a", "1: b"]
  1. A (element, index, wholeArray)
  2. B (index, element)
  3. C Only the element
  4. D (array, index)

Answer: A β€” (element, index, wholeArray)

All iteration methods pass (value, index, array). You may ignore the extras - most callbacks only use the value.

CallbacksParameters

Q14. medium

How do you sum an array of objects' prices?

const cart = [{price: 100}, {price: 250}];
const total = cart.reduce((s, i) => s + i.price, 0);   // 350
  1. A items.reduce((sum, item) => sum + item.price, 0)
  2. B items.sum("price")
  3. C items.map(i => i.price).total()
  4. D items.add(price)

Answer: A β€” items.reduce((sum, item) => sum + item.price, 0)

reduce with an accumulator starting at 0 is the standard total. Alternatively items.map(i => i.price).reduce((a,b) => a+b, 0).

reduceReal-world

Q16. medium

What does flatMap() do?

console.log(["a b", "c"].flatMap(s => s.split(" ")));
// ["a", "b", "c"]
  1. A Maps each element then flattens the result one level
  2. B Flattens only
  3. C Maps twice
  4. D Sorts and maps

Answer: A β€” Maps each element then flattens the result one level

flatMap is map + flat(1) in one pass - ideal when each input produces zero, one or many outputs.

flatMapflat

Q17. medium

How do you sort numbers ascending?

[10, 9, 100].sort((a, b) => a - b);   // [9, 10, 100]
[10, 9, 100].sort((a, b) => b - a);   // [100, 10, 9]
  1. A arr.sort((a, b) => a - b)
  2. B arr.sort()
  3. C arr.sort("asc")
  4. D arr.sortNumbers()

Answer: A β€” arr.sort((a, b) => a - b)

A comparator returning a negative number means 'a first', positive means 'b first', 0 means equal. a - b gives ascending; b - a gives descending.

sortComparator

Q18. medium

How do you sort an array of objects by a property?

users.sort((a, b) => a.age - b.age);
users.sort((a, b) => a.name.localeCompare(b.name));
  1. A arr.sort((a, b) => a.age - b.age) for numbers, or localeCompare for strings
  2. B arr.sort("age")
  3. C arr.sortBy(age)
  4. D arr.order(age)

Answer: A β€” arr.sort((a, b) => a.age - b.age) for numbers, or localeCompare for strings

Subtract for numeric fields; use a.name.localeCompare(b.name) for text so that accents and locale rules are handled correctly.

sortlocaleCompare

Q20. medium

Which methods do NOT mutate the original array?

  1. A map, filter, slice, concat, reduce, join
  2. B push, pop, splice, sort
  3. C All array methods mutate
  4. D No array methods mutate

Answer: A β€” map, filter, slice, concat, reduce, join

The functional methods return new values. The mutators are push, pop, shift, unshift, splice, sort, reverse and fill. Knowing which is which prevents surprise bugs.

ImmutabilityMutation

Q21. medium

What is the output? console.log([1, 2, 3].includes(2), [1, 2, 3].indexOf(2));

console.log([NaN].includes(NaN));   // true
console.log([NaN].indexOf(NaN));    // -1
  1. A true 1
  2. B 1 true
  3. C true true
  4. D 2 2

Answer: A β€” true 1

includes gives a boolean; indexOf gives the position. includes also finds NaN correctly, which indexOf cannot.

includesindexOfNaN

Q23. medium

What does Array.from() do?

Array.from("abc");                      // ["a","b","c"]
Array.from({length: 3}, (_, i) => i);    // [0, 1, 2]
Array.from(document.querySelectorAll("p"));
  1. A Creates an array from an iterable or array-like object, optionally mapping each item
  2. B Copies only arrays
  3. C Sorts an array
  4. D Converts an array to a string

Answer: A β€” Creates an array from an iterable or array-like object, optionally mapping each item

Array.from turns strings, Sets, Maps, NodeLists and {length: n} objects into real arrays, with an optional map function as the second argument.

Array.fromArray-like

Q26. medium

How do you find the maximum value in an array?

console.log(Math.max(...[3, 7, 2]));   // 7
console.log([3,7,2].reduce((m, x) => x > m ? x : m));   // 7
  1. A Math.max(...arr)
  2. B arr.max()
  3. C Math.max(arr)
  4. D arr.sort()[0]

Answer: A β€” Math.max(...arr)

Math.max takes separate arguments, so spread the array. Math.max(arr) would give NaN. For very large arrays use reduce to avoid argument limits.

Math.maxSpread

Q28. medium

What is the output? const users = [{name:"Ana", age:30}, {name:"Ben", age:20}]; console.log(users.map(u => u.name).join(", "));

  1. A "Ana, Ben"
  2. B ["Ana","Ben"]
  3. C "AnaBen"
  4. D Error

Answer: A β€” "Ana, Ben"

map extracts the names into an array, then join turns them into a readable string. Extract-then-join is an everyday pattern for displaying lists.

mapjoinReal-world

Q30. medium

Which method would you use to check if EVERY form field is filled?

  1. A fields.every(f => f.value.trim() !== "")
  2. B fields.some(...)
  3. C fields.filter(...)
  4. D fields.map(...)

Answer: A β€” fields.every(f => f.value.trim() !== "")

every returns true only when all elements pass - exactly 'is the whole form valid?'. some would answer 'is at least one filled?'.

everyValidation

Hard questions (11)

Q5. hard

Why should you pass an initial value to reduce()? arr.reduce(fn, 0)

[].reduce((a, b) => a + b);        // TypeError!
[].reduce((a, b) => a + b, 0);     // 0 - safe
  1. A Without it, reduce throws a TypeError on an EMPTY array and starts with element 0 otherwise
  2. B It is purely decorative
  3. C It makes reduce faster
  4. D It reverses the array

Answer: A β€” Without it, reduce throws a TypeError on an EMPTY array and starts with element 0 otherwise

With no initial value, the first element becomes the accumulator and an empty array raises 'Reduce of empty array with no initial value'. Passing 0 (or {} or []) also makes the intended type explicit.

reduceEdge cases

Q10. hard

What is the output? console.log([1, 2, 3].map(n => { n * 2; }));

n => n * 2         // implicit return
n => { return n * 2; }   // explicit return
n => { n * 2; }    // returns undefined!
  1. A [undefined, undefined, undefined] - the arrow body has braces but no return
  2. B [2, 4, 6]
  3. C [1, 2, 3]
  4. D SyntaxError

Answer: A β€” [undefined, undefined, undefined] - the arrow body has braces but no return

With curly braces you must write return explicitly. Concise bodies without braces return automatically: n => n * 2. A very common beginner bug.

Arrow functionsImplicit return

Q11. hard

How do you return an OBJECT from a concise arrow function?

const wrap = n => ({ value: n });
console.log([1,2].map(wrap));   // [{value:1},{value:2}]
  1. A Wrap it in parentheses: n => ({ value: n })
  2. B n => { value: n }
  3. C n => return { value: n }
  4. D It is impossible

Answer: A β€” Wrap it in parentheses: n => ({ value: n })

Without parentheses the braces are parsed as a function BODY, not an object literal (giving undefined). Parentheses tell JavaScript it is an expression.

Arrow functionsObject literals

Q13. hard

What is the output? console.log(["1", "2", "3"].map(parseInt));

  1. A [1, NaN, NaN] - map passes the index as parseInt's radix argument
  2. B [1, 2, 3]
  3. C ["1", "2", "3"]
  4. D [NaN, NaN, NaN]

Answer: A β€” [1, NaN, NaN] - map passes the index as parseInt's radix argument

map calls parseInt(value, index): parseInt("1",0)=1, parseInt("2",1)=NaN (radix 1 is invalid), parseInt("3",2)=NaN (3 is not a binary digit). Fix by wrapping: map(s => parseInt(s, 10)) or map(Number).

  • A famous interview question about accidental extra arguments.

parseIntCallbacksGotchas

Q15. hard

What does this reduce build? arr.reduce((acc, x) => { acc[x] = (acc[x] || 0) + 1; return acc; }, {})

const votes = ["a", "b", "a"];
console.log(votes.reduce((acc, v) => {
  acc[v] = (acc[v] || 0) + 1; return acc;
}, {}));   // { a: 2, b: 1 }
  1. A A frequency count object: { value: howManyTimes }
  2. B A sum
  3. C A sorted array
  4. D A filtered array

Answer: A β€” A frequency count object: { value: howManyTimes }

Starting with an empty object, each element increments its own counter. Counting occurrences is one of reduce's most useful patterns.

reduceCountingGrouping

Q19. hard

What is the output? const a = [3, 1, 2]; const b = a.sort(); b.push(9); console.log(a);

  1. A [1, 2, 3, 9] - sort mutates AND returns the SAME array, so a and b are one array
  2. B [3, 1, 2]
  3. C [1, 2, 3]
  4. D [9]

Answer: A β€” [1, 2, 3, 9] - sort mutates AND returns the SAME array, so a and b are one array

sort() sorts in place and returns a reference to the same array - it does not copy. Use [...a].sort() or a.toSorted() when you need to keep the original.

sortMutationReferences

Q22. hard

How do you get unique values, sorted, from [3,1,3,2]?

  1. A [...new Set([3,1,3,2])].sort((a,b) => a-b)
  2. B [3,1,3,2].unique().sort()
  3. C [3,1,3,2].filter(unique)
  4. D Set([3,1,3,2]).sort()

Answer: A β€” [...new Set([3,1,3,2])].sort((a,b) => a-b)

Set removes duplicates, spread converts back to an array, then sort with a numeric comparator gives [1, 2, 3]. Note a Set itself has no sort method.

SetsortChaining

Q24. hard

What is the output? console.log([1,2,3].reduce((a, b) => a + b));

  1. A 6 - without an initial value, the first element becomes the accumulator
  2. B TypeError
  3. C [1,2,3]
  4. D 0

Answer: A β€” 6 - without an initial value, the first element becomes the accumulator

Omitting the initial value starts with acc=1, b=2 (giving 3), then acc=3, b=3 (giving 6). It works for non-empty arrays, but always passing an initial value is safer.

reduceInitial value

Q25. hard

What does this do? arr.filter(Boolean)

console.log([0, "a", null, "b", ""].filter(Boolean));
// ["a", "b"]
  1. A Removes all falsy values (0, "", null, undefined, NaN, false)
  2. B Converts everything to booleans
  3. C Keeps only booleans
  4. D Throws an error

Answer: A β€” Removes all falsy values (0, "", null, undefined, NaN, false)

Boolean is passed as the callback: each element is converted, and only truthy ones survive. A clean idiom for cleaning data.

filterTruthiness

Q27. hard

What is the performance concern with chaining many array methods? arr.map(...).filter(...).map(...)

  1. A Each step creates a new array and iterates again - fine for small data, wasteful for very large arrays
  2. B It always crashes
  3. C Chaining is impossible
  4. D It mutates the original

Answer: A β€” Each step creates a new array and iterates again - fine for small data, wasteful for very large arrays

Three chained calls mean three passes and three temporary arrays. For typical UI data this is irrelevant and readability wins; for huge datasets a single reduce or for...of loop is more efficient.

PerformanceChaining

Q29. hard

How would you group items by a property using reduce?

const byType = items.reduce((acc, item) => {
  (acc[item.type] ||= []).push(item);
  return acc;
}, {});
  1. A reduce((acc, item) => { (acc[item.type] ||= []).push(item); return acc; }, {})
  2. B arr.groupBy("type")
  3. C arr.filter("type")
  4. D arr.sort("type")

Answer: A β€” reduce((acc, item) => { (acc[item.type] ||= []).push(item); return acc; }, {})

Create the array for a key if missing, then push. (Object.groupBy exists in very new environments, but the reduce pattern works everywhere.)

reduceGrouping

Practice β€œArray Methods” as a quiz