JavaScript function that lives on the prototype object of the Array class



Problem

We are required to write a JavaScript function that lives on the prototype object of the Array class. This function should take in a callback function and this function should return that very first element for which the callback function yields true.

We should feed the current element and the current index to the callback function as first and second argument.

Example

Following is the code −

 Live Demo

const arr = [4, 67, 24, 87, 15, 78, 3];
Array.prototype.customFind = function(callback){
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(callback(el, i)){
         return el;
      };
      continue;
   };
   return undefined;
};
console.log(arr.customFind(el => el % 5 === 0));

Output

15

Advertisements