Javascript is a prototype-based language. It means that every native function can receive custom functions or having its original functions modified.
In this article, we will create a custom filter function. For who doesn't know, the filter function is an array prototype function that returns all elements that match against the callback passed as argument. For more information about filter you can check the MDN Doc.
So, without further ado, let's code!
const data = [1, 2, 3, 4, 5];
Array.prototype.myCustomFilter = function (fn) {
const filtered = []; // it will receive all values that match to condition passed in fn callback.
for (let i = 0; i < this.length; i++) {
if (fn(this[i])) {
filtered.push(this[i]);
}
}
return filtered;
};
const filteredData = data.myCustomFilter(function (el) {
if (el > 2) return el;
});
// using arrow function
// const filteredData = data.myCustomFilter(el => el > 2);
console.log(filteredData); // output [3,4,5]
Easy, no? But, what really happened here?
Understanding the function
The filter function receives a callback as a parameter. You can find more info about callback here.
Here, we're saying to Array: "Hey dude, you're gonna get a new function called myCustomFilter and it takes a callback function as parameter".
Array.prototype.myCustomFilter = function (fn) {...}
The method filter will return all values that match to condition passed in the callback function.
And here is where the magic happens:
...
for (let i = 0; i < this.length; i++) {
if (fn(this[i])) {
filtered.push(this[i]);
}
}
...
Once loop has finished, a new array as result is returned containing all values matched to the condition.
const filteredData = data.myCustomFilter(function (el) {
if (el > 2) return el;
});
And finally our output will be:
console.log(filteredData); // output [3,4,5]
Using the original filter method, our function would become:
const originalFilteredData = data.filter(p => p > 2);
console.log(originalFilteredData); // output [3,4,5]
We cannot forget to mention it that we have some concepts not covered here as the context of this
and arrow functions
. These guys will be discussed in the future.
I hope you enjoy this article!!
That's all, folks!!!
trying to improve english skills too =D
Top comments (1)
Thanks Paz for this, I just learnt something from this.