Array Methods: map, filter & reduce
The power tools of modern JavaScript. map, filter and reduce appear everywhere — especially in React.
What you will learn
- Transform a list with map
- Select items with filter
- Combine into a total with reduce
map — transform every item
map creates a new array by transforming each item. (You will use this constantly in React to turn data into HTML.)
<script>
const prices = [100, 200, 300];
const withTax = prices.map(p => p * 1.18);
document.write(withTax.join(", "));
</script>map runs the little function p => p * 1.18 on every item: 100 becomes 118, 200 becomes 236, 300 becomes 354. It collects those into a brand-new array withTax. The original prices is untouched.
Note: Output: 118, 236, 354
filter — keep only some
filter runs a true/false test on each item and keeps only the ones that pass.
<script>
const nums = [4, 9, 12, 3, 20];
const big = nums.filter(n => n > 10);
document.write("Over 10: " + big.join(", "));
</script>For each number, the test n > 10 is checked. 4, 9 and 3 fail and are dropped; 12 and 20 pass and are kept. The result is a new, shorter array big containing just those two.
Note: Output: Over 10: 12, 20
reduce — boil down to one value
reduce combines a whole list into a single value — here, one running total.
<script>
const cart = [250, 100, 400];
const total = cart.reduce((sum, item) => sum + item, 0);
document.write("Total: ₹" + total);
</script>sum is a running tally that starts at 0 (the last argument). For each item, reduce does sum + item: 0+250 = 250, then 250+100 = 350, then 350+400 = 750. That final sum becomes total.
Note: Output: Total: ₹750
Tip: Mental model: map = change each item, filter = keep matching items, reduce = combine all into one. All three return a new array/value and leave the original alone.
Q. Which method creates a new array by transforming every item?
✍️ Practice
- Use
mapto convert an array of names to uppercase. - Use
filterto keep only the even numbers from a list. - Use
reduceto find the total of a list of prices.
🏠 Homework
- Given an array of student scores, use
filterto find who passed (≥40) andreduceto find the average.