Arrays & ObjectsCore· 45 min read

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.)

map: each price → price + 18% tax
<script>
  const prices = [100, 200, 300];
  const withTax = prices.map(p => p * 1.18);
  document.write(withTax.join(", "));
</script>
Live preview

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.

filter: keep items that pass the test
<script>
  const nums = [4, 9, 12, 3, 20];
  const big = nums.filter(n => n > 10);
  document.write("Over 10: " + big.join(", "));
</script>
Live preview

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.

reduce: add everything into one total
<script>
  const cart = [250, 100, 400];
  const total = cart.reduce((sum, item) => sum + item, 0);
  document.write("Total: ₹" + total);
</script>
Live preview

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?

Answer: map transforms each item and returns a new array of the results. filter selects; reduce combines into one value.

✍️ Practice

  1. Use map to convert an array of names to uppercase.
  2. Use filter to keep only the even numbers from a list.
  3. Use reduce to find the total of a list of prices.

🏠 Homework

  1. Given an array of student scores, use filter to find who passed (≥40) and reduce to find the average.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →