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

Asked

Viewed 39 times

3

I wonder if there is a problem if I add this method to javascript arrays, and if possible how do I do it? It’s something like this?

Array.prototype.search = function () {};
  • Can you explain what this method should do if the answers don’t match what you’re looking for?

  • It was just to check whether an array was holding a certain value or not.

  • ok, in this case both methods I have indicated do. The most semantic perhaps is the .includes for it simply returns true|false if the array stores this value or not.

  • thanks for the answers, before I had to make a loop for crazy, now facilitated.

1 answer

1


There are two methods with functionality that may be the one you are looking for:

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

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

Having said that, a method with the name search there is no.

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

But that can be implemented in a simplistic way, only 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.