Computer >> Computer tutorials >  >> Programming >> Javascript

Implementing a custom function like Array.prototype.filter() function in JavaScript


Problem

We are required to write a JavaScript function that lives on the prototype Object of the Array class.

Our function should take in a callback function as the only argument. This callback function should be called for each element of the array.

And that callback function should take in two arguments the corresponding element and its index. If the callback function returns true, we should include the corresponding element in our output array otherwise we should exclude it.

Example

Following is the code −

const arr = [5, 3, 6, 2, 7, -4, 8, 10];
const isEven = num => num % 2 === 0;
Array.prototype.customFilter = function(callback){
   const res = [];
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(callback(el, i)){
         res.push(el);
      };
   };
   return res;
};
console.log(arr.customFilter(isEven));

Output

[ 6, 2, -4, 8, 10 ]