14 The map, filter, and reduce functions
Lesson goal Understand what map, filter and reduce do, and learn to implement them yourself: declaratively, imperatively and recursively with a trampoline.
The most frequently used functions in functional programming and production code are map, filter, and reduce.
These functions provide powerful capabilities for working with data.
map
The map function returns a new object of the same data type, passing each element through the function it receives as an argument when the type is iterable. If the type is not iterable, the contained data is simply passed through the function.
Let's implement the map function in several different ways.
// currying and taking the data as the last argument
// make these functions easy to use in composition
// in point-free style, without naming the data:
// pipe (mapD (f), filterD (g))
// ==== declarative implementation ====
// mapD :: (a -> b) -> [a] -> [b]
const mapD = (fn) => (arr) => arr.map(fn)
// ===================================
// ==== imperative implementation ====
// without the iteration index and context
// mapI :: (a -> b) -> [a] -> [b]
const mapI = (fn) => (arr) => {
// the resulting array
// that we will return
let result = []
for (const item of arr) {
// pass each element through
// the given function
result.push(fn(item)) // or result = [ ...result, fn (item) ]
}
return result
}
// ===================================
// ==== imperative implementation ====
// with the iteration index and context
// mapIq :: ((a, Number, [a]) -> b) -> [a] -> [b]
const mapIq = (fn) => (arr) => {
let result = []
for (let i = 0; i < arr.length; i++ ) {
result.push(fn(arr[i], i, arr)) // or result = [ ...result, fn (arr[i], i, arr) ]
}
return result
}
// ===================================
// ==== recursive implementation ====
// through a trampoline, so the stack does not overflow
// I hope you have read the lesson on recursion
// trampoline :: ((...args -> *) -> (...args -> *))
// calls the function and, while the result is a function (a thunk),
// calls it again: the steps run in a loop, the stack does not grow
const trampoline = (fn) => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
// mapR returns either the finished array
// or a function with no arguments (a thunk) holding the next step
const mapR = (fn) => (arr, i = 0, acc = []) => {
// base case
// when the elements run out, return the accumulator
if (i === arr.length) {
return acc
}
// recursive case
// return a function for the trampoline
// put the result of passing the element through the function into the accumulator
// and move on to the next element
// an index instead of arr.slice(1) and push instead of [...acc, x]:
// copying the array on every step would make it O(n²),
// and acc is created anew on every run and is not visible outside
return () => {
acc.push(fn (arr[i]))
return mapR (fn) (arr, i + 1, acc)
}
}
// mapTrampoline :: (a -> b) -> [a] -> [b]
// from the outside we pass only the array: the index and the accumulator are internal
const mapTrampoline = (fn) => (arr) => trampoline (mapR (fn)) (arr)
// ===================================
// ==== run ====
const data = [1, 2, 3, 4, 5]
const result = mapD (v => v * 2) (data)
console.log (result) // [2, 4, 6, 8, 10]
// ===================================filter
The filter function returns a new object of the same data type, passing each element through a predicate function and keeping only the elements for which the predicate returned true (the type is iterable).
A predicate is a function that returns true or false. It is usually passed as an argument to a higher-order function such as filter: in JavaScript functions are first-class values, so they can be passed around like any other value.
Let's implement the filter function in several different ways.
// currying and taking the data as the last argument
// make these functions easy to use in composition
// in point-free style, without naming the data:
// pipe (mapD (f), filterD (g))
// ==== declarative implementation ====
// filterD :: (a -> Boolean) -> [a] -> [a]
const filterD = (fn) => (arr) => arr.filter(fn)
// ===================================
// ==== imperative implementation ====
// without the iteration index and context
// filterI :: (a -> Boolean) -> [a] -> [a]
const filterI = (fn) => (arr) => {
// the resulting array
// that we will return
let result = []
for (const item of arr) {
// pass each element through
// the predicate function
// if it returns true, put the element
// into the resulting array
if (fn(item)) {
result.push(item) // or result = [ ...result, item ]
}
}
return result
}
// ===================================
// ==== imperative implementation ====
// with the iteration index and context
// filterIq :: ((a, Number, [a]) -> Boolean) -> [a] -> [a]
const filterIq = (fn) => (arr) => {
let result = []
for (let i = 0; i < arr.length; i++ ) {
const value = arr[i]
if (fn(value, i, arr)) {
result.push(value) // or result = [ ...result, value ]
}
}
return result
}
// ===================================
// ==== recursive implementation ====
// through a trampoline, so the stack does not overflow
// I hope you have read the lesson on recursion
// trampoline :: ((...args -> *) -> (...args -> *))
// calls the function and, while the result is a function (a thunk),
// calls it again: the steps run in a loop, the stack does not grow
const trampoline = (fn) => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
// filterR returns either the finished array
// or a function with no arguments (a thunk) holding the next step
const filterR = (fn) => (arr, i = 0, acc = []) => {
// base case
// when the elements run out, return the accumulator
if (i === arr.length) {
return acc
}
// recursive case
// return a function for the trampoline
return () => {
// the current element
const head = arr[i]
// put the element into the accumulator
// if the predicate function returned true,
// otherwise the accumulator stays the same
if (fn (head)) {
acc.push(head)
}
// move on to the next element
// an index and push instead of [head, ...tail] and [...acc, head]:
// copying the array on every step would make it O(n²)
return filterR (fn) (arr, i + 1, acc)
}
}
// filterTrampoline :: (a -> Boolean) -> [a] -> [a]
// from the outside we pass only the array: the index and the accumulator are internal
const filterTrampoline = (fn) => (arr) => trampoline (filterR (fn)) (arr)
// ===================================
// ==== run ====
const data = [1, 2, 3, 4, 5]
const result = filterD (v => v > 3) (data)
console.log (result) // [4, 5]
// ===================================reduce
The reduce function can return any data type; it takes a function and an accumulator as its arguments.
As arguments, the function takes the accumulator (from the initial value or from subsequent calls) and the current element, passes this data through the function's logic, and returns a new accumulator or applies changes to the current accumulator.
The accumulator (the initial value) can be any value.
With reduce you can emulate any custom behavior, as well as the behavior of map and filter. But it is usually used to collect specific data according to a particular logic from an iterable object type.
// currying and taking the data as the last argument
// make these functions easy to use in composition
// in point-free style, without naming the data:
// pipe (mapD (f), filterD (g))
// ==== declarative implementation ====
// reduceD :: ((a, b) -> a) -> a -> [b] -> a
const reduceD = (fn) => (init) => (arr) => arr.reduce(fn, init)
// ===================================
// ==== imperative implementation ====
// without the iteration index and context
// reduceI :: ((a, b) -> a) -> a -> [b] -> a
const reduceI = (fn) => (init) => (arr) => {
// the value we will return
// starts with the initial value
let accumulator = init
for (const item of arr) {
// call the function
// with the accumulator as the first argument
// and the current array element as the second
// store the result in the accumulator
// so the next call builds on the previous result
accumulator = fn (accumulator, item)
}
return accumulator
}
// ===================================
// ==== imperative implementation ====
// with the iteration index and context
// reduceIq :: ((a, b, Number, [b]) -> a) -> a -> [b] -> a
const reduceIq = (fn) => (init) => (arr) => {
let accumulator = init
for (let i = 0; i < arr.length; i++ ) {
accumulator = fn (accumulator, arr[i], i, arr)
}
return accumulator
}
// ===================================
// ==== recursive implementation ====
// through a trampoline, so the stack does not overflow
// I hope you have read the lesson on recursion
// trampoline :: ((...args -> *) -> (...args -> *))
// calls the function and, while the result is a function (a thunk),
// calls it again: the steps run in a loop, the stack does not grow
const trampoline = (fn) => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
// reduceR returns either the final value
// or a function with no arguments (a thunk) holding the next step
const reduceR = (fn) => (init) => (arr, i = 0) => {
// base case
// when the elements run out, return the accumulator
if (i === arr.length) {
return init
}
// recursive case
// return a function for the trampoline
return () => {
// the accumulator we will return:
// pass the old accumulator and the current value
// through the function
const nextInit = fn (init, arr[i])
// call the function again
// with the same function,
// the new accumulator
// and the next index: an index instead of [head, ...tail],
// so the array is not copied on every step
return reduceR (fn) (nextInit) (arr, i + 1)
}
}
// reduceTrampoline :: ((a, b) -> a) -> a -> [b] -> a
// from the outside we pass only the array: the index is internal
// a limitation of the trampoline: if the final value is itself a function,
// the trampoline takes it for the next step and calls it
const reduceTrampoline = (fn) => (init) => (arr) => trampoline (reduceR (fn) (init)) (arr)
// ===================================
// ==== run ====
const data = [1, 2, 3]
const result = reduceD ((a, b) => a + b) (0) (data)
console.log (result) // 6
// ===================================Key points
- map returns a new object of the same data type, passing each element through the given function.
- filter returns a new object of the same data type and keeps only the elements for which the predicate returned true.
- reduce takes a function and an accumulator and can return any data type; with it you can emulate both map and filter.
- Currying and taking the data as the last argument let you use these functions in composition in point-free style, without naming the data.
- The recursive versions run through a trampoline and walk the array by index: copying the array on every step would make them O(n²).
Exercises
Exercise 1
The lesson says that reduce can emulate map and filter. Write curried functions mapVia and filterVia that take the data as the last argument and use only reduce inside. Then use pipe to build an onlineNames function from them that returns the names of the users who are online.
Starter code
// pipe from the "Function composition" lesson
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)
const users = [
{ name: 'John', status: 'online', age: 28 },
{ name: 'Angel', status: 'online', age: 35 },
{ name: 'Michel', status: 'offline', age: 18 },
{ name: 'Anna', status: 'offline', age: 20 },
]
// mapVia :: (a -> b) -> [a] -> [b]
const mapVia = (fn) => (arr) => {
// your code
}
// filterVia :: (a -> Boolean) -> [a] -> [a]
const filterVia = (fn) => (arr) => {
// your code
}
// onlineNames :: [Object] -> [String]
const onlineNames = pipe(
// your code: filterVia and mapVia
)
console.log(onlineNames(users))
console.log(mapVia((n) => n * 2)([1, 2, 3]))Expected output
[ "John", "Angel" ] [ 2, 4, 6 ]
Show solution
// pipe from the "Function composition" lesson
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)
const users = [
{ name: 'John', status: 'online', age: 28 },
{ name: 'Angel', status: 'online', age: 35 },
{ name: 'Michel', status: 'offline', age: 18 },
{ name: 'Anna', status: 'offline', age: 20 },
]
// the [] accumulator is created anew on every call and is not visible outside,
// so pushing into it changes nobody's data
// mapVia :: (a -> b) -> [a] -> [b]
// pass each element through fn and put the result into the accumulator
const mapVia = (fn) => (arr) =>
arr.reduce((acc, item) => {
acc.push(fn(item))
return acc
}, [])
// filterVia :: (a -> Boolean) -> [a] -> [a]
// only the elements for which the predicate returned true get into the accumulator
const filterVia = (fn) => (arr) =>
arr.reduce((acc, item) => {
if (fn(item)) {
acc.push(item)
}
return acc
}, [])
// onlineNames :: [Object] -> [String]
// point-free style: we don't name the data, it comes into pipe last
const onlineNames = pipe(
filterVia((user) => user.status === 'online'),
mapVia((user) => user.name),
)
console.log(onlineNames(users))
console.log(mapVia((n) => n * 2)([1, 2, 3]))Exercise 2
reduce can return any data type, an object for example. Write a curried function countBy: its first argument is a function that returns an element's key, its second is an array, and it uses reduce to return an object that shows, for each key, how many elements produced it. Count the users by status, and the numbers from 1 to 5 by parity.
Starter code
const users = [
{ name: 'John', status: 'online', age: 28 },
{ name: 'Angel', status: 'online', age: 35 },
{ name: 'Michel', status: 'offline', age: 18 },
{ name: 'Anna', status: 'offline', age: 20 },
]
// countBy :: (a -> String) -> [a] -> Object
const countBy = (fn) => (arr) => {
// your code
}
console.log(countBy((user) => user.status)(users))
console.log(countBy((n) => (n % 2 === 0 ? 'even' : 'odd'))([1, 2, 3, 4, 5]))Expected output
{
"online": 2,
"offline": 2
}
{
"odd": 3,
"even": 2
}Show solution
const users = [
{ name: 'John', status: 'online', age: 28 },
{ name: 'Angel', status: 'online', age: 35 },
{ name: 'Michel', status: 'offline', age: 18 },
{ name: 'Anna', status: 'offline', age: 20 },
]
// countBy :: (a -> String) -> [a] -> Object
// the accumulator is a {} object, created anew on every call
const countBy = (fn) => (arr) =>
arr.reduce((acc, item) => {
// the key of the current element
const key = fn(item)
// a key gets 1 the first time, then its counter grows by one
acc[key] = (acc[key] ?? 0) + 1
return acc
}, {})
console.log(countBy((user) => user.status)(users))
console.log(countBy((n) => (n % 2 === 0 ? 'even' : 'odd'))([1, 2, 3, 4, 5]))Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.