Topic 20 of 37
map, filter, reduce
Overview
JavaScript arrays come with built-in higher-order functions that allow you to process data declaratively (telling the computer WHAT to do, rather than HOW to do it). These methods do not mutate the original array, but instead return a new array (or value), making your code functional and predictable.
Syntax
.map and .filter always return a new array. .reduce can return anything (a number, object, string, or array) based on your accumulator.
The Holy Trinity of Array Methods
javascript
const numbers = [1, 2, 3, 4, 5];
// .map(): Transforms every element
const doubled = numbers.map(num => num * 2);
// [2, 4, 6, 8, 10]
// .filter(): Keeps elements that pass a test
const evens = numbers.filter(num => num % 2 === 0);
// [2, 4]
// .reduce(): Accumulates elements into a single value
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
// 15Common Pitfalls
- Forgetting to return a value inside .map() or .filter(), resulting in an array of undefined.
Interview Tips
- Be prepared to chain these methods: e.g., filter for active users, then map to get their emails.
Real-World Example
Processing an API response to render UI components in React.
example
javascript
const users = [{ name: "Alice", active: true }, { name: "Bob", active: false }];
function ActiveUsersList() {
return (
<ul>
{users
.filter(user => user.active)
.map(user => <li key={user.name}>{user.name}</li>)}
</ul>
);
}