As a JavaScript developer most of us are pretty familiar with filter method of JavaScript. Like the code below.
let num = [1,2,3,4,5,6];
num.filter(x=> x>2 );
console.log(num); // output is [3,4,5,6]
In the above function we have simply inbuilt filter method which we make to filter out array num
. Now what if we need a customizable filter function that accept a function just like the filter method. So lets start. Below code is the same method we would do using filter method but instead of filter method we are using customFilter
which we are going to build.
let myResult = [1,2,3,4,5,6].customFilter(function(element, index, arr) {
return element > 2;
});
In order to build array method we need to make sure where it is derived from other wise it will throw an error saying customFilter
is not a function. To create array method we need to derived from array prototype. If we had to create custom method for Date we would need to create Date.prototype
. But we will be using Array.prototype
for this example.
Array.prototype.customFilter = function(fn){
console.log(fn); //
// output:
// function (element, index, arr) {
// return element > 2;
// }
console.log(this); // return [1,2,3,4,5,6]
}
Now we have a customFilter
method for an array which accept an argument as an function. Note when we console log fn
it will return function expression because we must receive the function as parameter but when we console this
keyword it will return array. Now lets start the actual filter process.
Array.prototype.customFilter = function(fn) {
let newFilter = [];
for(let i=0; i<this.length; i++) {
if(fn(this[i], i, this)) {
newFilter.push(this[i]);
}
}
return newFilter;
}
I have pass 3 argument to fn
function. The first one is each array item which is denoted by this[i]
, the second one is array item index which is denoted by i
and the third one is the entire array itself which id denoted by this
keyword. So the the fn
function return true
we will push that value to newFilter
array. After that loop is completed we will have updated value return over customerFilter
method.
The whole code in one place.
Array.prototype.customFilter = function(fn) {
let newFilter = [];
for(let i=0; i<this.length; i++) {
if(fn(this[i], i, this)) {
newFilter.push(this[i]);
}
}
return newFilter;
}
let num = [1,2,3,4,5,6];
let greaterNum = num.customFilter(function(arrayItem, arrayIndex, arrayData){
return arrayItem > 2
})
let lastItem = num.customFilter((arrayItem, arrayIndex, arrayData)=> arrayData[arrayData.length-1]);
let lastItem = num.customFilter((arrayItem, arrayIndex, arrayData)=> arrayData[0]);
console.log(greaterNum); // [3,4,5,6]
console.log(lastItem); // [6]
console.log(firstItem); // [1]
I hope the creating custom prototype is clear. If you have any question do share in comment.