Loading article...
The filter() method creates a new array with all elements that pass the test implemented by the provided callback function. This polyfill replicates the native behavior, including support for thisArg and proper handling of sparse arrays.
Array.prototype.myFilter = function(callback, thisArg) { if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } let result = []; for (let i = 0; i < this.length; i++) { if (this.hasOwnProperty(i)) { // Ensures only actual elements are processed if (callback.call(thisArg, this[i], i, this)) { result.push(this[i]); } } } return result; };
const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.myFilter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4, 6]
myFilter method is added to Array.prototype, making it available on all arrays.(element, index, array) as arguments.thisArg :thisArg parameter is used to bind a custom this context when executing the callback function.this.hasOwnProperty(i) to ensure that only actual elements are processed.callback argument is a valid function.TypeError, mimicking the behavior of the native Array.prototype.filter method.This polyfill behaves similarly to the native Array.prototype.filter, allowing for array filtering based on a custom condition. It handles thisArg, ensures correct element processing in sparse arrays, and performs type checking on the callback.
Test your understanding with 3 quick questions