Looping over an array to build a new one is so common that arrays have methods for it. To use them you need a shorter way to write small functions.
Arrow functions
An arrow function is a compact function without a name:
const double = (n) => n * 2;
console.log(double(5)); // 10
Before the arrow => are the parameters. After it is the value to return. No function, no braces and no return needed for a one-line calculation.
map: change every item
map runs a function on each item and collects the results in a new array of the same length:
const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.2);
// [12, 24, 36]
filter: keep some items
filter runs a test on each item and keeps only the ones where the test is true:
const big = prices.filter((p) => p > 15);
// [20, 30]
Neither method changes the original array.
Other useful ones
.join(", ")glues all items into one string, with the given text between them..find((x) => …)returns the first item that passes the test..sort()puts strings in alphabetical order..reduce((sum, x) => sum + x, 0)boils an array down to one value, here the total.
These methods can be chained: the result of one becomes the input of the next.
const names = ["li", "omar", "eve"];
console.log(names.map((n) => n.toUpperCase()).join(" & ")); // LI & OMAR & EVE
Your Task
- Use
filterto createadults: only the ages that are 18 or more. - Use
mapto createnextYear: every age fromages, plus 1. - Print
adults, then printnextYear.
adultsholds only the ages of 18 and over- It is made with
filter nextYearholds every age plus 1- It is made with
map, andagesitself is unchanged - Both arrays are printed
Lesson complete!
Next Lesson: Objects