Polyfill for Array.filter

JavaScript array has an inbuilt method filter() which takes a callback function as input and returns a new array with the all elements the has passed the test implemented in the callback function.

Example

const arr = [1, 2, 3, 4, 5, 6];
const filtered = arr.filter((e) => e % 2 === 0);
console.log(filtered);

//[2, 4, 6]

I have checked what arguments this callback takes and found that this callback function takes three arguments, element, index of the element, and the original array itself.

We can see that in this image.

Polyfill array filter

Array.filter polyfill

It is extremely common question in JavaScript interviews where it is asked to implement polyfill for the filter() method.

A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers.

Array.filter polyfill should have these three functionalities.

  • The filter() function should take an callback function as an argument.
  • Current element, its index, and the context should be passed as an argument to the callback function.
  • All the elements which pass text implemented in this callback function should be returned in a new array.
Array.prototype.filter = function (callback) {
  //Store the new array
  const result = [];
  for (let i = 0; i < this.length; i++) {
    //call the callback with the current element, index, and context.
    //if it passes the text then add the element in the new array.
    if (callback(this[i], i, this)) {
      result.push(this[i]);
    }
  }
  
  //return the array
  return result
}