map, filter, and reduce (sometimes called fold) are fundamental higher-order functions in functional programming, especially when working with collections like arrays. They allow you to process data in a declarative and often more readable way.
Let's break down each one, their differences, and then touch upon "all other" related concepts.
1. map
- Purpose: Transformation (one-to-one). It creates a new array by applying a function to each element of the original array.
- Input: An array.
- Output: A new array of the same length as the original. Each element in the new array is the result of applying the callback function to the corresponding element in the original array.
- Callback Function: Takes an element and returns a transformed value for that element.
- Analogy: An assembly line where each product goes through the same process and comes out as a modified product.
Example (JavaScript):
const numbers = [1, 2, 3, 4];
// Double each number
const doubledNumbers = numbers.map(num => num * 2);
// doubledNumbers is now [2, 4, 6, 8]
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// Get only the names
const userNames = users.map(user => user.name);
// userNames is now ['Alice', 'Bob', 'Charlie']
console.log('Original numbers:', numbers); // [1, 2, 3, 4] (original is unchanged)
2. filter
- Purpose: Selection / Filtering (one-to-many, keeping a subset). It creates a new array containing only the elements from the original array that satisfy a given condition.
- Input: An array.
- Output: A new array whose length is less than or equal to the original array's length.
- Callback Function: Takes an element and returns a boolean (
true to keep the element, false to discard it).
- Analogy: A sieve that lets through only the items that meet specific criteria. Or a bouncer at a club, letting in only those who pass the check.
Example (JavaScript):
const numbers = [1, 2, 3, 4, 5, 6];
// Keep only even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);
// evenNumbers is now [2, 4, 6]
const products = [
{ name: 'Laptop', price: 1200 },
{ name: 'Mouse', price: 25 },
{ name: 'Keyboard', price: 750 }
];
// Find products under $100
const affordableProducts = products.filter(product => product.price < 100);
// affordableProducts is now [{ name: 'Mouse', price: 25 }]
console.log('Original numbers:', numbers); // [1, 2, 3, 4, 5, 6] (original is unchanged)
3. reduce (or fold)
- Purpose: Aggregation / Accumulation (many-to-one). It reduces an array down to a single value by applying a function that accumulates a result over each element.
- Input: An array, and optionally an initial value for the accumulator.
- Output: A single value (can be any type: number, string, object, array, etc.).
- Callback Function: Takes two arguments:
accumulator: The value returned from the previous callback invocation (or the initial value).
currentValue: The current element being processed.
It returns the updated accumulator.
- Initial Value: Highly recommended. If not provided,
reduce starts accumulating from the first element, using the first element as the initial accumulator.
- Analogy: A blender or melting pot where you throw in many ingredients and end up with one final dish/substance.
Example (JavaScript):
const numbers = [1, 2, 3, 4];
// Sum all numbers
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// sum is now 10 (0 + 1 + 2 + 3 + 4)
// Concatenate strings
const words = ['Hello', ' ', 'World', '!'];
const sentence = words.reduce((acc, word) => acc + word, '');
// sentence is now 'Hello World!'
const votes = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob', 'Alice'];
// Count votes for each person
const voteCounts = votes.reduce((acc, name) => {
acc[name] = (acc[name] || 0) + 1;
return acc;
}, {}); // Initial accumulator is an empty object
// voteCounts is now { Alice: 3, Bob: 2, Charlie: 1 }
console.log('Original numbers:', numbers); // [1, 2, 3, 4] (original is unchanged)
Key Differences Summary
| Feature | map | filter | reduce |
|---|
| Purpose | Transformation | Selection/Filtering | Aggregation/Accumulation |
| Output | New array (same length) | New array (same or shorter length) | Single value (any type: number, string, object, etc.) |
| Callback | Returns transformed item | Returns boolean (true to keep) | Returns updated accumulator |
| Arguments to Callback | (item) | (item) | (accumulator, item) |
| Initial Value | Not applicable | Not applicable | Often required/recommended |
| Use Cases | Change data format, derive values | Subset data, find matches | Calculate sums/counts, build objects, flatten arrays |
| Original Array | Immutable (does not modify) | Immutable (does not modify) | Immutable (does not modify) |
"All Other" - Related Concepts & Why These Three are Special
map, filter, and reduce are often grouped because they represent the core operations for transforming, selecting, and aggregating data collections in a functional and immutable way. They are higher-order functions (functions that take other functions as arguments or return functions).
Here are some "all other" common array methods and concepts, and how they relate or differ:
-
forEach:
- Difference: Unlike
map, filter, and reduce, forEach does not return a new array or a value. Its primary purpose is to execute a provided function once for each array element, typically for side effects (e.g., logging to console, updating a DOM element).
- Use Case: Iterating over an array when you don't need a return value, but need to perform an action.
- Example:
numbers.forEach(num => console.log(num));
-
find / findIndex:
- Difference: While
filter returns a new array containing all elements that match a condition, find returns only the first element that satisfies the condition (or undefined if none). findIndex returns the index of the first element.
- Use Case: When you expect at most one matching element.
- Example:
users.find(user => user.id === 2); // Returns the Bob object.
-
some / every:
- Difference: These methods return a single boolean value based on whether any (
some) or all (every) elements in the array satisfy a condition.
- Use Case: Checking for the presence of certain elements or validating all elements meet a criteria.
- Example:
numbers.some(num => num > 5); // true (because 6 is > 5)
numbers.every(num => num > 0); // true (all numbers are positive)
-
sort:
- Difference:
sort reorders the elements of an array. Crucially, in JavaScript, sort() modifies the original array in place by default. To maintain immutability (like map, filter, reduce), you often chain it after creating a shallow copy: .
Why map, filter, reduce are Preferred in Functional Programming:
- Immutability: They do not modify the original array, which leads to more predictable code and fewer side effects. This is a cornerstone of functional programming.
- Declarative Style: They describe what you want to achieve (e.g., "double all numbers," "keep even numbers," "sum all numbers") rather than how to do it (e.g., using
for loops with explicit index manipulation and temporary variables).
- Readability: Once understood, their intent is often clearer than equivalent
for loops.
- Composability/Chaining: They can be easily chained together to perform complex data transformations in a single, fluent line of code.
// Example of chaining map and filter
const complexTransformation = numbers
.filter(num => num % 2 === 0) // First, filter for even numbers
.map(num => num * 3) // Then, triple the remaining even numbers
.reduce((sum, num) => sum + num, 0); // Finally, sum them up
// For [1, 2, 3, 4, 5, 6]:
// filter -> [2, 4, 6]
// map -> [6, 12, 18]
// reduce -> 36
In essence, map, filter, and reduce are powerful tools for transforming and aggregating data collections in a clean, functional, and immutable manner, making your code more robust and easier to reason about.