Array Methods: map, filter, reduce & Beyond
JS جاوااسکریپت

Array Methods: map, filter, reduce & Beyond

Chain transformations, explain complexity, and implement polyfills interviewers still ask for.

BugCast Admin··۵ دقیقه مطالعه

Array methods are the bread and butter of JavaScript interviews. You should know what each returns, whether it mutates, and how to implement map and reduce from scratch.

Common Interview Questions

Q: map vs forEach?

Answer: map returns a new array of transformed values. forEach returns undefined and is for side effects. Prefer map when building a new collection.

Q: Implement Array.prototype.map

Answer: Respect sparse arrays with i in this. Return a new array without mutating the original.


Array.prototype.myMap = function (cb, thisArg) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this) result.push(cb.call(thisArg, this[i], i, this));
  }
  return result;
};

Q: reduce use cases beyond summing?

Answer: Grouping, flattening, building lookup maps, composing pipelines, and counting frequencies — reduce is the general-purpose accumulator.

Q: Which methods mutate the array?

Answer: push, pop, shift, unshift, splice, sort, reverse, fill, and copyWithin. filter, map, slice, and concat do not.

Key Points for Interviews

  • Know return values and mutation behavior cold

  • find/findIndex short-circuit; some/every too

  • Chaining should stay readable — extract named steps if long

  • flatMap maps then flattens one level

  • Big-O is usually O(n) per pass — multiple chains multiply

#arrays#functional#interview

مطالب مرتبط