Syncing account progress…

Back

Beginner · 8 min

Transform and filter arrays

Use arrow functions with map() and filter() to process a collection.

Transform each value

An arrow function is another way to write a function. With an expression after =>, the result is returned automatically. map() creates a new array by applying a function to every item.

const prices = [2, 4, 6];
const doubled = prices.map(price => price * 2);
console.log(doubled.join(", "));

Output

4, 8, 12

Keep matching values

filter() creates a new array containing the items whose test returns true. Neither this filter nor the earlier map changes the original numeric array.

const prices = [5, 12, 8, 20];
const affordable = prices.filter(price => price <= 10);
console.log(affordable.join(", "));

Output

5, 8

Put it into practice

  1. Predict the output of each example before running it.
  2. Complete the coding task, then try the practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Select affordable prices

Use filter() to keep prices at or below 10. Display them joined with ", ".

Practice