How to Use Map, Filter, and Reduce in JavaScript
In JavaScript,
map creates a new array by applying a function to each element, filter creates a new array with elements that pass a test, and reduce combines all elements into a single value using a function. These methods help process arrays cleanly and efficiently.Syntax
map: array.map(callback(element, index, array)) - transforms each element and returns a new array.
filter: array.filter(callback(element, index, array)) - selects elements that return true in the callback.
reduce: array.reduce(callback(accumulator, element, index, array), initialValue) - reduces array to a single value by accumulating results.
javascript
const newArray = array.map(element => element * 2); const filteredArray = array.filter(element => element > 5); const sum = array.reduce((acc, element) => acc + element, 0);
Example
This example shows how to double numbers with map, keep only numbers greater than 10 with filter, and sum all numbers with reduce.
javascript
const numbers = [1, 5, 10, 15]; // Double each number const doubled = numbers.map(num => num * 2); // Keep numbers greater than 10 const filtered = doubled.filter(num => num > 10); // Sum all numbers const total = filtered.reduce((acc, num) => acc + num, 0); console.log('Doubled:', doubled); console.log('Filtered:', filtered); console.log('Total:', total);
Output
Doubled: [2, 10, 20, 30]
Filtered: [20, 30]
Total: 50
Common Pitfalls
- Not returning a value inside the
maporfiltercallback causesundefinedor empty results. - For
reduce, forgetting the initial value can cause errors or unexpected results. - Using
mapwhen you want to filter or reduce leads to wrong outputs.
javascript
const arr = [1, 2, 3]; // Wrong: map without return const wrongMap = arr.map(num => { num * 2; }); console.log(wrongMap); // [undefined, undefined, undefined] // Right: map with return const rightMap = arr.map(num => num * 2); console.log(rightMap); // [2, 4, 6] // Wrong: reduce without initial value on empty array // [].reduce((acc, val) => acc + val); // Throws error // Right: provide initial value const sum = [].reduce((acc, val) => acc + val, 0); console.log(sum); // 0
Output
[undefined, undefined, undefined]
[2, 4, 6]
0
Quick Reference
| Method | Purpose | Returns | Callback Arguments |
|---|---|---|---|
| map | Transforms each element | New array | element, index, array |
| filter | Selects elements by test | New array | element, index, array |
| reduce | Combines elements to one value | Single value | accumulator, element, index, array |
Key Takeaways
Use
map to create a new array by changing each element.Use
filter to keep only elements that meet a condition.Use
reduce to combine all elements into one value.Always return a value inside
map and filter callbacks.Provide an initial value to
reduce to avoid errors.