Hiprup

How do you implement Array.filter from scratch?

filter returns a new array with only the elements that pass a test.

  1. Create an empty result array.

  2. Loop the original by index.

  3. Call the callback with (element, index, array); if it returns truthy, push the element.

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

Like map: it's non-mutating and passes index and array to the callback.

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;
};

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

// With index
const unique = nums.myFilter((n, i, arr) => arr.indexOf(n) === i);

For each element, call the callback. If it returns true (truthy), add the element to the result array. callback.call(thisArg, ...) sets the this context. i in this handles sparse arrays.

A new array is returned — the original is never modified.

Similar to myMap: iterate, call callback, conditionally push. Key difference: filter pushes the ORIGINAL element (not the callback result).

The i in this check handles sparse arrays. The callback signature is (element, index, array).

How do you implement Array.filter from scratch? | Hiprup