Everything you need to know about Map, Filter & Reduce
After reading this blog you will be pretty clear about the higher order functions like Map, Filter & Reduce.
So lets start with Map.
1. Map
Basics:
Basically it executes a function on each element of an array.
It returns a new array with the same length.
Use case:
When we want to perform the same operation on each element of array and get back a new array of the same length with the transformed values.
Example:
var numbers = [1,2,3,4,5];
var doubled_arr = numbers.map(n => n * 2);
console.log(doubled_arr);
// output
[2,4,6,8,10]
2. Filter
Basics:
- It executes a function on each element of an array.
- It removes items which don't satisfy a condition and returns filtered array.
Use case:
You have an array and want to filter out certain items. The result is a new array with the same items, but with some excluded.
Example:
var numbers = [1,2,3,4,5];
var greaterThanTwo = numbers.filter(n=> n > 2);
console.log( greaterThanTwo);
// Output
[3,4,5]
3. Reduce
Basics:
- We need to declare the initial value of the accumulator.
- On each iteration, inside the callback we perform some operation and that will be added to the accumulator.
- Returns a single value as output.
Example:
Var numbers = [1,2,3,4,5];
var initialVal = 0;
let result = numbers.reduce(( acc ,val )=> val + acc, initialVal);
console.log(result);
// Output
15