Lesson 16 of 34 · Arrays
JavaScript Array map, filter and reduce
Most of the time you don't loop over an array just for fun. You loop to transform every item, select some items or combine them all into one result. JavaScript has a dedicated method for each job: map, filter and reduce.
They're higher-order functions, so you already know the key idea: you pass in a callback, and the method calls it for every item.
map: transform every item
map calls your callback on each item and collects the return values into a new array of the same length:
const prices = [10, 25, 40];
const withTax = prices.map((price) => price * 1.2);
console.log(withTax); // [ 12, 30, 48 ]
const names = ["ada", "linus"];
console.log(names.map((name) => name.toUpperCase())); // [ 'ADA', 'LINUS' ]
The original array is untouched: prices is still [ 10, 25, 40 ].
filter: keep the items you want
filter calls your callback on each item and keeps only the items where the callback returns a truthy value. The result is a new array that may be shorter:
const levels = [3, 18, 7, 25, 12];
const veterans = levels.filter((level) => level >= 10);
console.log(veterans); // [ 18, 25, 12 ]
If nothing matches, you get an empty array [], never undefined.
reduce: combine everything into one value
reduce walks through the array while carrying an accumulator, a running result. Your callback receives the accumulator and the current item and returns the new accumulator. The second argument to reduce is the starting value:
const gold = [5, 10, 20];
const total = gold.reduce((sum, coins) => sum + coins, 0);
console.log(total); // 35
Step by step: sum starts at 0, then becomes 0 + 5 = 5, then 5 + 10 = 15, then 15 + 20 = 35.
The accumulator can be anything: a number, a string, an array or an object. Here it tracks the maximum:
const best = [4, 9, 2].reduce((max, n) => (n > max ? n : max), -Infinity);
console.log(best); // 9
Chaining
Because map and filter return arrays, you can call the next method directly on the result. Read the chain top to bottom like a recipe:
const damageRolls = [4, 12, 7, 15, 2];
const bigHitsTotal = damageRolls
.filter((roll) => roll >= 7) // [ 12, 7, 15 ]
.map((roll) => roll * 2) // [ 24, 14, 30 ]
.reduce((sum, roll) => sum + roll, 0);
console.log(bigHitsTotal); // 68
The callback's extra arguments
All three methods pass more than just the item. map and filter callbacks receive (item, index, array), and reduce callbacks receive (accumulator, item, index, array). Most of the time you only need the first one or two.
Common mistakes
- Forgetting
returnin a block body.nums.map((n) => { n * 2 })produces[ undefined, undefined, … ]. Use(n) => n * 2or addreturn. - Using
mapjust to loop. If you don't use the returned array, you wantforEachorfor...of. - Leaving out reduce's starting value. Without it,
reduceuses the first item as the start, and on an empty array it throwsTypeError: Reduce of empty array with no initial value. - Expecting the original to change.
mapandfilterreturn new arrays. Store the result.
Assignment
Write four functions using map, filter and reduce:
squareAll(numbers)returns a new array with every number squared.squareAll([1, 2, 3])→[1, 4, 9].longWords(words, minLength)returns only the words with at leastminLengthcharacters.longWords(["sun", "dragon", "elf", "wizard"], 4)→["dragon", "wizard"].sum(numbers)returns the total of all numbers.sum([5, 10, 15])→30, andsum([])→0.sumOfEvenSquares(numbers)returns the sum of the squares of the even numbers only.sumOfEvenSquares([1, 2, 3, 4])→20(that's 2² + 4²).
None of the functions may change the array they receive.
Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Transforming collections in other languages
- Python List Comprehensions · Python
- Java Lambdas and Streams Basics · Java
- LINQ in C#: Where, Select, OrderBy, GroupBy and Aggregate · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .