Home >Web Front-end >JS Tutorial >Polyfill for Map, Filter, and Reduce Methods in Javascript
It returns new array from original array, by performing some operations( callback function) on each array items. It does not alter the original array.
const nums = [1, 2, 3, 4]; const double = nums.map((num, i, arr) => num * 2); console.log(double); // [2, 4, 6, 8]
Array.prototype.myMap = function (cb) { let output = []; for (let i = 0; i < this.length; ++i) { output.push(cb(this[i], i, this)); } return output; };
It returns a new array containing only the elements that satisfy the given condition (i.e., for which the callback returns true). The original array remains unchanged.
const nums= [1, 2, 3, 4]; const greaterThan2 = nums.filter((num, i, arr) => num > 2); console.log(greaterThan2); // [3, 4]
Array.prototype.myFilter = function (cb) { let output = []; for (let i = 0; i < this.length; ++i) { if (cb(this[i], i, this)) output.push(this[i]); } return output; };
It is probably the most complicated of all three. This method processes an array’s elements to produce a single output value.
const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, num) => acc + num, 0); console.log(sum); // 10
Array.prototype.myReduce = function (cb, initialValue) { let accumulator = initialValue; for (let i = 0; i < this.length; ++i) { accumulator = accumulator!== undefined ? cb(accumulator, this[i], i, this) : this[i]; } return accumulator; };
The above is the detailed content of Polyfill for Map, Filter, and Reduce Methods in Javascript. For more information, please follow other related articles on the PHP Chinese website!