Categories
interview

Array.filter() polyfill

Array.prototype.filter = function(callback, context) {
  const ret = [];
  for (let index = 0; index < this.length; index++) {
    if (callback.call(context, this[index], index, this)) {
      ret.push(this[index]);
    }
  }
  return ret;
};

console.log([4, -1, 1, 2, 3].filter(x => x >= 2)); // [4, 2, 3];

Demo