map(), reduce(), filter() in JavaScript
cheat sheet for map(), reduce(), filter() methods in JavaScript
map()
It accepts a callback function once for each array element and returns a new array.
The
map()
method doesn’t execute the function for an empty array.
item
- It’s a required parameter, the value of the current array item.index
- Optional, It’s the current index of the array element that is being processed.arr
- Optional, the array on which themap()
method was called.
let arr = [10, 20, 30, 40, 50, 60];
let half = arr.map(function(item){
return item/2
});
// half: [ 5, 10, 15, 20, 25, 30 ]
reduce()
The
reduce()
method executes a reducer function on each element of the array.It returns a single value as a result and doesn’t execute the function for an empty array element.
accumulator
- It’s a value of the previous function call, or theInitialValue
for the first call.If there is no any
InitialValue
provided then it’s accumulate the first item of the array anditem
is initialized to the second value in the array.
item
- It’s a required parameter, that is the value of the current item of the array.index
- Optional, it’s the current index of the array element that is being processed.arr
- Optional, the array on which thereduce()
method was called.InitialValue
- Optional, it’s a starting value that is used to initialize the callback function for the first time.
const inr = [10, 20, 30, 40, 50, 60];
const totalINR = inr.reduce(function(total, item){
return total + item
}, 0);
// totalINR: 210
filter()
The
filter()
method returns an array that passes the condition. If no elements pass the condition, it returns an empty array.It doesn’t execute the callback function for empty elements.
item
- It’s a required parameter, the value of the current array item.index
- Optional, It’s the current index of the array element that is being processed.arr
- Optional, the array on which thefilter()
method was called.
const user = ["Ajay", "Sivam", "Anuj", "Shankar"];
let nameStartWithA = user.filter(function(name){
return name.startsWith("A");
});
// nameStartWithA: [ 'Ajay', 'Anuj' ]