Q3: Implement a polyfill for Array.prototype.filter().
Answer
The filter() method creates a new array containing the elements for which the callback returns a truthy value.
Array.prototype.myFilter = function (callback, thisArg) {
if (this == null) {
throw new TypeError("Array.prototype.myFilter called on null or undefined");
}
if (typeof callback !== "function") {
throw new TypeError("Callback must be a function");
}
const array = Object(this);
const length = array.length >>> 0;
const result = [];
for (let i = 0; i < length; i++) {
if (i in array) {
const value = array[i];
if (callback.call(thisArg, value, i, array)) {
result.push(value);
}
}
}
return result;
};
console.log([1, 2, 3, 4, 5].myFilter(n => n % 2 === 0));
// [2, 4]
Explanation
Unlike map(), which produces one output slot for every existing input element, filter() only includes elements that pass the condition.
The implementation skips holes in sparse arrays and passes the value, index, and original array to the callback.
Key Takeaways
- Filter returns a new array containing only matching elements.
- The callback's truthiness determines whether an element is retained.