Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading