javascript string.indexOf (array) does not work with long strings

3

I was looking for a good time but all the questions were different from mine.

I'm trying to find a string in an array where the strings within the array contain more than one word, for example:

var array = ["hola soy un string", " asd hola asd " , "hola"]

if I do:

array.indexOf("hola")

I will return 2, okay.

But, if my array is like this:

var array = ["hola asd", "asdasd hola", "aaxs hola asdxas"]

array.indexOf("hola");

does not return anything despite the fact that "hello" is, why is this?

Also try this way:

array.map(function(i) { return i; }).indexOf("hola");

But more of the same, it did not work.

    
asked by Darcyys 09.11.2016 в 10:50
source

2 answers

5

Array.indexOf( ) returns the first exact match within an array.

[ 'hola', 'adios' ].indexOf( 'hola' ) => 0
[ 'hola', 'adios' ].indexOf( 'ios' ) => -1

You have no choice but to go through the entire Array, element by element, using a loop:

idx = -1;
while( curr = Array[++idx] )
 if( COMPROBACIÓN QUE BUSCAS ) {
  ...
 }
    
answered by 09.11.2016 / 11:08
source
1

If you look at the documentation of indexOf you can see that it returns the index of the first position it finds with the string that you are looking for.

ex:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("e"); // n =  1

But you apply it to a array , then it returns the index of the element that matches what you are looking for. When you had the array with an element "hola" I found it, but then having "aaxs hola asdxas" you can not find it

    
answered by 09.11.2016 в 10:56