An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
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=0let 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;};
Original Link: https://dev.to/unalo_baayriyo/foreach-map-filter-and-reduce-in-javascript-gi9
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To