Searching in an array in javascript

1

How to do a search within an array in javascript?

The solution I use is a gambiarra.

x = ['a','b','c','d'];

if ( x.indexOf('a') != -1) {

    console.log('Verdadeiro');

} else {
    console.log('Falso');
}
    
asked by anonymous 04.09.2016 / 05:26

3 answers

1

Jonas, the way you're using is the historically correct way.

There is now a new way, which is already available in most browsers, which is .includes() " and that is part of ECMAScript 2016. With this new syntax you could use:

x = ['a','b','c','d'];

if (x.includes('a')) console.log('Verdadeiro');
else console.log('Falso');
    
04.09.2016 / 08:47
0

You can do this using the filter function of javascript.

var x = ['a','b','c','d'];
//passando como parâmetro a função que implementa a condição que você quer
var filter = x.filter(function(p){ return p == 'a'});
//Caso não encontre, o retorna vai ser um array vazio
if(filter.lenght > 0){
  console.log("Verdadeiro");
}
else{
  console.log("Falso");
}
    
04.09.2016 / 08:35
0

It is correct to use Array().indexOf , this is the only way to find the index of a specific element in a Array by traversing it.

So you could make a polyfill to work on all browsers.

Edit: I had to grow the polyfill code because MSIE6 is a fairly narrow browser. i++ , instead of incrementing i after returning its own value, returns i incremented.

if (!Array.prototype.indexOf)

    Array.prototype.indexOf = function(item) {
        var me = this;
        /* Percore a array até achar um item igual à @item. */
        for (var i = 0, l = me.length; i < l && (me[i] === item ? false : true); i++);
        return i < l ? i : -1;
    };
    
04.09.2016 / 14:59