filter picks the items you want from a list: the unread messages, the products in stock, the users who match a search. Writing it yourself shows how the built-in decides what counts as a pass, why its result never has holes, and what it does with array-like objects and bad arguments.
Write Array.prototype.myFilter(callback, thisArg) in filter.js. It must behave like the built-in Array.prototype.filter for every case below.
myFilter returns a new array, even when every item passes, and leaves the original array unchanged.
An item is kept when the callback returns any truthy value (1, "yes", an object), and dropped for any falsy value (0, "", null, undefined, NaN).
The callback receives the value, its index and the array (the same object), with thisArg as its this. The callback itself is called, as the built-in does, even when it has its own call property.
Holes are skipped, and the result is packed: kept values sit at indexes 0, 1, 2… An index that holds undefined is an item, not a hole.
length is read once, before the loop: items pushed during the call are not visited, and an item deleted before the loop reaches it is skipped.
The value stored in the result is the value passed to the callback, even if the callback then changes the array.
myFilter works on any object with a length (an array-like object, or a string), called with Array.prototype.myFilter.call(…). length is converted to a whole number from 0 up: "2" is 2, 2.9 is 2, -1 and a missing length are 0. A length that is a BigInt or a Symbol, or an object whose valueOf returns one, throws a TypeError, as the built-in does.
It throws a TypeError when the callback is not a function (even for an empty array), and when it is called on null or undefined.
An error thrown by the callback stops the loop and reaches the caller unchanged.
Plain JavaScript in a browser page; the tests call Array.prototype.myFilter from filter.js.
filter.js starts with "use strict". Keep it: in strict mode, this inside myFilter is exactly the value it was called on, so a call on null can be detected.
Not allowed: the built-in filter, forEach, flatMap and reduce. The tests delete them from Array.prototype while myFilter runs. Write the loop yourself.
Out of scope: subclasses of Array (the built-in creates the result through Symbol.species; myFilter always returns a plain array).