JavaScript Intermediate: Data, the DOM and Events
Array Methods: map, filter, reduce
In this lesson you will
- Transform arrays with map and filter
- Find and test items with find, some and every
- Combine values with reduce and sort safely
Introduction
A for loop works, but most JavaScript programmers reach for array methods instead. They say what you want ("keep the even numbers") rather than how to do it, and the code reads almost like English.
The simple explanation
Array methods take a function and apply it to every item.
The function you pass in is called a callback.
forEach
forEach runs a callback for each item. It does not return anything.
map: transform every item
map makes a new array by running a callback on each item and collecting the results. The original is not changed.
Quick quiz
What does map return?
filter: keep some items
filter returns a new array with only the items for which the callback returns true.
find, some and every
findreturns the first matching item (orundefined).someasks "does at least one match?".everyasks "do all match?".
reduce: boil down to one value
reduce combines all the items into a single value. The callback receives a running total (the accumulator) and the current item. You give it a starting value as the second argument.
Step by step: start at 0, add 1, add 2, add 3, add 4, giving 10.
Chaining
Because map and filter return arrays, you can chain them.
Quick quiz
Which method would you use to keep only the items that pass a test?
Sorting: a classic surprise
sort changes the array in place. By default it sorts items as text, so numbers go wrong:
To sort numbers, pass a compare function: (a, b) => a - b for ascending order. The [...nums] part makes a copy, so the original is not changed.
Try it yourself
Given a list of scores, print the passing scores (50 or more), the average of all scores, and the highest score.
Summary
forEachruns code per item.maptransforms,filterselects.find,someandeverysearch and test.reducecombines everything into one value.sortneeds a compare function for numbers. Copy first with[...array]to avoid changing the original.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading