javascript – Can I create a search method for arrays or does this method already exist for arrays?

Question:

I would like to know if there is any problem if I add this method to arrays in javascript, and if possible how do I do it? Is it something like that?

Array.prototype.search = function () {};

Answer:

There are two methods with functionality that might be what you're looking for:

  • the .find (ES5) method that looks for a condition and returns the first element that fulfills that condition.

  • the .includes (ES6) method that looks for an element and returns true|false , similar to what was done "before" with .indexOf(el) != -1 .

Having said that, a method named search does not exist.

To implement methods in the prototype you can define a function where this will be the array where you want to use the method. For example, for the .includes method there is a .includes for old browsers, quite complex because the method has a second argument to start the search from a given index.

But that can be implemented in a simplistic way, just to know if a given element is in an array or not, like this:

Array.prototype.search = function(el){
  return this.indexOf(el) != -1;
}

var respostaA = [1, 2, 3, 4, 5].search(3);
var respostaB = [1, 2, 3, 4, 5].search(6);

console.log(respostaA); // true
console.log(respostaB); // false
Scroll to Top