Hi Everyone,
If you work with arrays in TypeScript (or JavaScript), you'll run into map, filter, and reduce pretty often. These methods make it easy to manipulate data without writing messy loops. But knowing when and how to use them will take your coding game to the next level!
Let’s break down these methods step-by-step with examples and see when each one is useful.
What are map, filter, and reduce?
These three are array methods that allow you to,
- Transform data with a map
- Filter out unwanted elements with a filter
- Crunch down an array into a single value using a reduce
They’re all about functional programming—writing clean, readable code by working with immutable data (meaning they don’t change the original array).
Map - Transform Your Data
The map method creates a new array by applying a function to every element of the original array.
When to use a map?
Use a map when you want to transform each element of an array and return a new array with the transformed values.
Example. Doubling numbers in an array.
const numbers: number[] = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
What happened? We took each number in the original numbers array and doubled it. map returned a new array: [2, 4, 6, 8].
Filter. Keep Only What You Need
The filter method creates a new array with only the elements that pass a certain condition.
When to use a filter?
Use a filter when you need to remove elements that don’t match a given condition.
Example. Finding even numbers.
const numbers: number[] = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
What happened? We used a filter to keep only the even numbers. The result is a new array [2, 4].
Reduce - Crunch Data Into a Single Value
The reduce method reduces an array to a single value by accumulating results over time.
When to use reduce?
Use reduce when you need to accumulate values (like summing up numbers) or transform an array into something else (like an object).
Example. Summing all numbers.
const numbers: number[] = [1, 2, 3, 4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 10
Join the conversation! Your thoughts help the community grow.