An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
Brush up map, filter and reduce in 5 minutes
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:
Original Link: https://dev.to/rohanjsx/brush-up-map-filter-and-reduce-in-5-minutes-f3c
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To