Hiprup

How do you implement Array.filter from scratch?

filter returns a new array of the elements that pass a test.

  1. Create an empty result array.

  2. Loop the original by index.

  3. If callback(element, index, array) is truthy, push the element.

  4. Return the new array; the original is untouched.

Non-mutating, like map — it just keeps elements instead of transforming them.

Array.prototype.myFilter = function(callback, thisArg) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this && callback.call(thisArg, this[i], i, this)) {
      result.push(this[i]);
    }
  }
  return result;
};

console.log([1, 2, 3, 4, 5].myFilter(n => n > 3));     // [4, 5]
console.log([1, 2, 3, 4, 5].myFilter(n => n % 2 === 0)); // [2, 4]

Iterates each element. If callback returns truthy, pushes the ORIGINAL element to result.

Returns a new array (no mutation). callback.call for this binding. i in this for sparse arrays. Pushes the element itself (unlike map which pushes the callback's return value).

Key: push the ORIGINAL element (not the callback result — that is map). callback must return truthy to include. New array returned, original unchanged.