Array methods
Array methods
.map(fn)makes a new array by transforming each item..filter(fn)makes a new array of only the items wherefnreturnstrue..forEach(fn)runsfnfor each item, making no new array.
let nums = [1, 2, 3];
let doubled = nums.map((n) => n * 2);
console.log(doubled); // → [2,4,6]
Filtering keeps some items
.filterkeeps each item for which the test returnstrue.
let nums = [3, 7, 2, 9];
let big = nums.filter((n) => n > 4);
console.log(big); // → [7,9]
Watch out
.mapand.filtercreate a new outer array. They do not themselves rewrite the input, but a callback can mutate it. An object included in the result can still be the same object as in the input.- You hand each one an arrow function that says what to do with one item.
Common mistakes
- A new array does not imply new objects inside it.
filterkeeps the original object references;map(row => row)does too. To change flat object values independently, return a new object from the callback. forEachcalls the callback for each present element and returnsundefined; returning a value inside the callback does not create a result array.
Trace the shared objects
const rows = [{name: "Li", score: 4}];
const selected = rows.filter(row => row.score > 0);
selected[0].score = 9;
console.log(rows[0].score); // 9: the same object
console.log(selected === rows); // false: different outer arrays
const copies = rows.map(row => ({name: row.name, score: row.score + 1}));
copies[0].score = 20;
console.log(rows[0].score); // still 9: a different flat object
row.score += amount; return row;changes the input object, even insidemap. Returning{name: row.name, score: row.score + amount}creates a separate flat object. Nested objects would still need their own copying strategy.
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write double_all(nums) using .map. Return a new array with every number doubled; leave nums unchanged. For [1, 2, 3], return [2, 4, 6].
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Use .filter to keep only the numbers greater than 4 from [3, 7, 2, 9, 1], in a variable big (it should be [7, 9]).
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Use .forEach to add every number in [4, 8, 15] to total (it should end up 27).
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write raise_scores(rows, amount). Each row has only name (a string) and score (a number). Return a new array of new objects, keeping each name and adding amount to its score. Leave the input objects unchanged. For [{name: "Li", score: 4}] and 3, return [{name: "Li", score: 7}].
Click Run to see the output here.