23
ForEach, Map, Filter and Reduce in Javascript
ForEach, Map, reduce, and filter are all array methods in JavaScript. Map, reduce, and filter will iterate over an array and perform a transformation or computation and return some value while ForEach is used to just iterate over an array.
ForEach: ForEach method executes a provided function once for each array element.
ex:
let arrA = [1,2,3,4]
arrA.forEach(element => console.log(element));
// [1,2,3,4]
Map: Execute on each element of array and return new array with same length.
let arrA = [1,2,3,4]
let arrB = arrA.map(_i => i*2)
console.log(arrB)
// [1,4,6,8]
Filter: Filter basically return new array with elements which satisfy condition or filter out the elements which not satisfy the condition.
let arrA = [1,2,3,4]
let arrB = arrA.filter(_i => i%2)
console.log(arrB)
// [2,4]
Reduce: Reduce basically return a single value. While using it we have do define a initial value of accumulator and in each iteration we have to perform some operation and that will be added to accumulator.
let arrA = [1,2,3,4]
let initialVal=0
let result = arrA.reduce((accu, val) => val + accu , initialVal);
console.log(result)
// 10
Polyfill for ForEach, Map, Filter and Reduce
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.
Array.prototype.customForEach = function(callback) {
for (var i = 0; i < this.length; i++)
callback(this[i], i, this);
};
Array.prototype.customMap = function(callback) {
arr = [];
for (var i = 0; i < this.length; i++)
arr.push(callback(this[i], i, this));
return arr;
};
Array.prototype.customFilter = function(callback, context) {
arr = [];
for (var i = 0; i < this.length; i++) {
if (callback.call(context, this[i], i, this))
arr.push(this[i]);
}
return arr;
};
Array.prototype.customReduce = function(callback, initialVal) {
var accum = (initialVal === undefined) ? undefined : initialVal;
for (var i = 0; i < this.length; i++) {
if (accum !== undefined){
accum = callback.call(undefined, accum, this[i],
i, this);
} else{
accum = this[i];
}
}
return accum;
};
23