Categories
interview

Js filter() polyfill

Array.prototype.filter = function(callback, context) {
  const ret = [];
  for (const [key, val] of Object.entries(this)) {
    if (callback.call(context, this[key], key, this)) {
      ret.push(val);
    }
  }
  return ret;
};

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

Demo