DEV Community

Maaz Khan
Maaz Khan

Posted on

Polyfill for Map, Filter, and Reduce Methods in Javascript

Map

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]
Enter fullscreen mode Exit fullscreen mode

Implementation

Array.prototype.myMap = function (cb) {
  let output = [];
  for (let i = 0; i < this.length; ++i) {
    output.push(cb(this[i], i, this));
  }
  return output;
};

Enter fullscreen mode Exit fullscreen mode

Filter

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]
Enter fullscreen mode Exit fullscreen mode

Implementation

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;
};
Enter fullscreen mode Exit fullscreen mode

Reduce

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
Enter fullscreen mode Exit fullscreen mode

Implementation

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;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Unfortunately, none of these implementations duplicate the JS built-in equivalents

Collapse
 
maazkhan profile image
Maaz Khan • Edited

Oh really? Thanks for pointing that out!
For interview, I think these implementations are sufficient. I also updated the post title to avoid any confusion.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

They're not good polyfills either. Both filter and map are missing a parameter (thisValue). Using these polyfills could easily break code.