Implement custom Array.prototype.filter
Implement a custom myFilter
function that works like the built-in Array.prototype.filter
method.
Array.prototype.filter
is a method that creates a new array with all elements that pass the test implemented by the provided function, e.g. filter all numbers greater than 3:
const numbers = [1, 2, 3, 4, 5];
const filtered = numbers.myFilter((number) => {
return number > 3;
});
console.log(filtered); // Output: [4, 5]
Solution
To implement myFilter
, we need to iterate over the array and call the callback function for each element to check if it passes the test. If the callback function returns true
, we add the element to the new array.
Algorithm:
- Initialize an empty array to store the result.
- Iterate over the array.
- For each element, call the callback function to check if it passes the test.
- It runs the callback with arguments: (element, index, array)
- If the callback function returns
true
, add the element to the result array.
- Return the result array.
Implementation
Array.prototype.myFilter = function(callback) {
const result = [];
// `this` refers to the array on which myFilter is called
for (let i = 0; i < this.length; i++) {
// Check if the current element passes the test
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
// Example of usage
const numbers = [1, 2, 3, 4, 5];
const filtered = numbers.myFilter((number) => {
return number > 3;
});
console.log(filtered); // Output: [4, 5]
Summary
myFilter
iterates through the array.- For each element, it runs the callback with (element, index, array).
- If the callback returns
true
, the element is added to the result. - It returns a new array, just like the built-in
filter
.