Lesson 42 +15 XP

Array Iteration

Array Iteration

Iteration methods let you run code for every item in an array.

forEach

Runs a function for each element:

["a", "b", "c"].forEach(function(item) {
  console.log(item);
});

map

Creates a NEW array from the results of a function:

let doubled = [1, 2, 3].map(n => n * 2);
// doubled is [2, 4, 6]

filter

Creates a new array with only items that pass a test:

let evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
// evens is [2, 4]

find

Returns the first item that passes a test:

[3, 7, 11].find(n => n > 5); // 7

reduce

Combines all items into one value:

let total = [1, 2, 3].reduce((sum, n) => sum + n, 0);
// total is 6

map vs filter

  • map transforms every item.
  • filter keeps only some items.

TL;DR

  • forEach runs code for each item.
  • map builds a new transformed array.
  • filter keeps matching items.
  • find gets the first match.
  • reduce combines items into one value.