In Javascript, arrays have a number of methods that are like the higher-order functions you wrote yesterday.
find
Takes a one-argument predicate, i.e. a function that takes one
argument and returns true
or false
.
Returns the first value in the array for which the predicate returns
true
or undefined
if none do.
const ns = [1, 2, 3, 4]
ns.find((n) => n % 2 === 0) ⟹ 2
ns.find((n) => n > 10) ⟹ undefined
(This is basically firstMatching
from the other day.)
filter
Takes a one-argument predicate, i.e. a function that takes one
argument and returns true
or false
.
Returns an array containing only those elements of the original array for which the predicate returns true.
const ns = [1, 2, 3, 4]
ns.filter((n) => n % 2 === 0) ⟹ [2, 4]
map
Takes a one-argument function.
Returns an array of same size as the original but with new values produced by calling the function on each of the original elements.
const ns = [1, 2, 3, 4]
ns.map((n) => n ** 2) ⟹ [1, 4, 9, 16]
reduce
Takes a two-argument function and an initial value.
Returns a value produced by repeatedly calling the function with to either the initial value or the previous value returned by the function and the next element of the array.
const ns = [1, 2, 3, 4]
ns.reduce((tot, n) => tot + n, 0) ⟹ 10
flatMap
Takes a one-argument function that returns an array.
Returns an array with the elements of all the arrays returned by calling the function on each of the elements of the original array flattened into a single array.
const ns = [1,2,3,4]
ns.flatMap((x) => [x, x]) ⟹ [1, 1, 2, 2, 3, 3, 4, 4]
every
Takes a predicate function.
Returns a boolean which is true, if and only if the predicate returns true for every element of the array.
const ns = [1,2,3,4]
ns.every((n) => n % 2 === 0) ⟹ false
some
Takes a predicate function.
Returns a boolean which is true, if and only if the predicate returns true for some element of the array.
const ns = [1,2,3,4]
ns.some((n) => n % 2 === 0) ⟹ true
Start with some definitions:
const ns = [1,2,3,4]
const isEven = (n) => n % 2 === 0
const square = (n) => n ** 2;
const add = (a, b) => a + b;
Then:
ns.filter(isEven) ⟹ [2, 4]
ns.filter(isEven).map(square) ⟹ [4, 16]
ns.filter(isEven).map(square).reduce(add, 0) ⟹ 20
for
loop patternsCompare what you can do with these methods with the for loop patterns you learned back in first semester.