← Back to libraryQuestion 139 of 468
🟨JavaScriptIntermediate

Array Methods: map, filter, reduce

📌 Definition:

map, filter, and reduce are higher-order array methods for transforming data functionally without mutating the original array. map transforms each element, filter selects elements, and reduce folds an array into a single value.

📖 Detailed Explanation:

map(fn) returns a new array of the same length where each element is the result of fn — use it to transform (e.g., extract a field). filter(fn) returns a new array containing only elements for which fn returns truthy — use it to select. reduce(fn, initial) walks the array carrying an accumulator, returning one final value (a sum, an object, a grouped structure, even another array) — it is the most general of the three. All three are pure (they do not modify the source array) and chainable, which makes data pipelines readable: data.filter(...).map(...).reduce(...).

🔑 Key Points:
  • map: transform each item → new array (same length)
  • filter: keep items passing a predicate → new (shorter/equal) array
  • reduce: fold to a single value with an accumulator
  • All return new arrays and can be chained; none mutate the source
🌍 Real-World Example:

Turning an API list of user objects into a count of active users by role: users.filter(u => u.active).reduce((acc, u) => { acc[u.role] = (acc[u.role] || 0) + 1; return acc; }, {}). One readable pipeline replaces a manual loop with mutable counters.

🎯 Scenario-Based Interview Question:

Given const nums = [1, 2, 3, 4, 5], use map/filter/reduce to get the sum of squares of the even numbers.