Sikau

JavaScript · Day 33 · about 25 min

map and filter

Transforming and choosing items.

Loops in one line

Two jobs come up constantly: change every item (double each price) and keep only some items (just the vegetarian dishes). Arrays have built-in methods for both, and they take a callback.

map: change every item

const prices = [100, 250, 80];
const withTax = prices.map((p) => p * 1.13);
console.log(withTax);

const names = ["asha", "bikash"];
console.log(names.map((n) => n.toUpperCase()));

The flour mill: map is like a mill: every grain that goes in comes out changed, and the same number come out as went in.

The rest of this lesson

  • filter: keep some itemsexplain
  • How map and filter call your functionexplain
  • Predict the outputpredict
  • Chainedpredict
  • Your turnwrite code
  • Keep the cheap oneswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript