Intro
In this blog we will understand how
map
, filter
and reduce
work by writing polyfils for them.A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
map
The
map()
method creates and returns a new array populated with the results of calling a provided function on every element in the calling array.Parameters
Parameter | Description |
callback function | Function that is called for every element of array. Each time callbackFunction executes, the returned value is added to newArray .
The function is called with the following arguments: |
currentValue | Required
The value of the current element. |
Return Value
Type | Description |
array | The results of a function for each array element. |
const array = [1, 2, 3, 4]; // pass a function to map const mapResult = array.map(x => x * 2); console.log(mapResult); // output: Array [2, 4, 6, 8]
Let’s understand this by writing a polyfill for
map
.Array.prototype.myMap = function (callbackFunction) { let newArray = [] for ( let i = 0; i < this.length; i++ ) { newArray.push(callbackFunction(this[i], i, this)) } return newArray }
filter
The
filter()
method creates a new array filled with elements that pass a the callback provided. It creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided callback function.Parameters
Parameter | Description |
callback function | Function is a predicate, to test each element of the array. Return a value that coerces to true to keep the element, or to false otherwise.
The function is called with the following arguments: |
currentValue | Required
The value of the current element. |
Return Value
Type | Description |
array | The results of a function for each array element. |
const array = [1, 2, 3, 4]; // pass a function to filter const filterResult = array.map(x => x > 2); console.log(filterResult); // output: Array [1,2]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
Let’s understand this by writing a polyfill for
filter
Array.prototype.myFilter = function (callbackFunction) { let newArray = [] for ( let i = 0; i < this.length; i++ ) { if(callbackFunction(this[i], i, this)) { newArray.push(this[i]) } } return newArray }
reduce
The
reduce()
method executes a "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
Lets understand this by adding a array of numbers
const array = [1, 2, 3, 4]; const initialValue = 0; const reducer = (previousValue, currentValue) => previousValue + currentValue // 0 + 1 + 2 + 3 + 4 const sum = array.reduce(reducer,initialValue); console.log(sum); // expected output: 10
Parameters
Parameter | Description |
initialValue | A value to which previousValue is initialized the first time the callback is called. If initialValue is specified, that also causes currentValue to be initialized to the first value in the array. If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array. |
callback function | A "reducer" function called with the following arguments: |
previousValue | Required
The value of the current element. |
currentValue | Optional
The index of the current element. |
currentIndex | Optional
The array of the current element. |
array | Optional
The array being traversed. |
Return Value
Type | Description |
single value | The value that results from running the "reducer" callback function to completion over the entire array. |
Let’s understand this by writing a polyfill for
reduce
Array.prototype.myReduce = function (reducerCallback, initialValue) { let accumulator = initialValue for ( let i = 0; i < this.length; i++ ) { accumulator = accumulator ? reducerCallback(accumulator, this[i], i, this) : this[0] } return accumulator }
map vs forEach
Both
map
and forEach
are methods that let us loop through an array and execute a callback function.The main difference between
map
and forEach
is that map returns an array but forEach does not.const array = [1,2,3,4,5] const mapResult = array.map(x => x + 1) const forEachResult = array.forEach(x => x + 1) console.log(mapResult) // [2,3,4,5,6] console.log(forEachResult) // undefined
The forEach callback function still runs but it just does not return anything, it returns
undefined.
conclusion
- The
map()
method creates and returns a new array populated with the results of calling a provided function on every element in the calling array.
- The
filter()
method creates a new array filled with elements that pass a the callback provided. It creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided callback function.
- The
reduce()
method executes a "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
- Both
map
andforEach
are methods that let us loop through an array and execute a callback function. The main difference betweenmap
andforEach
is that map returns an array but forEach does not.