Map, reduce, and filter are all array methods in JavaScript. Each one iterates over an array and performs a transformation or computation and returns a new array based on the result of the function.
Map
map method is used to create a new array from an existing one by applying a function to each element of the existing array.
The callback function takes 3 arguments:
- current element
- index
- the actual array
Polyfill for map() :
Filter
filter method takes each element in an array and applies a conditional statement against it. If the condition is fulfilled, only then the element is pushed to the result array.
The callback function for filter takes the same 3 arguments as map();
Polyfill for filter() :
Reduce
reduce method reduces an array of elements down to a single output value. reduce() takes 2 arguments: the callback function & an initial value. If the initial value is not provided by the user, the first element of the array is taken as the initial value. The callback function takes 4 arguments:
- accumulator (result of previous computations)
- current element
- index
- the actual array
Polyfill for reduce() :
Example to sum it up:
Top comments (0)