Search code examples
javascriptfindprototype

How to create custom find method?


I'm trying to create custom find method using Array.prototype, I tried a lot of way but i just couldn't break the loop for the first match:

let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
Array.prototype.myFind = function (callback) {
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this);
  }
};
arr.myFind((element, index, array) => {
  if (element[0] === "T") {
    console.log(`This is ${element} in index of ${index} in array ${array}`);
  }
});


Solution

  • Well right now you just have a for loop, if you want to find any element that satisfies a condition, you have to return a boolean from your callback and return the element, for which that returned boolean is true. If you want the index of the element you found and the initial array to be returned as well, you can return an object and destructure it:

    let arr = ["Bill", "Russel", "John", "Tom", "Eduard", "Alien", "Till"];
    Array.prototype.myFind = function (callback) {
      for (let i = 0; i < this.length; i++) {
        if ( true == callback(this[i], i, this)) {
          return {element:this[i],index:i,array:this};
        }
      }
    };
    let {element,index,array} = arr.myFind((element) => element[0] === "T");
    
    console.log(`This is ${element} in index of ${index} in array ${array}`);