How to check each character of an array? Javascript

Asked

Viewed 1,186 times

0

Person, I’m with this code:

const arrayOne = ['jean','geleia','gean','ea games', 'e1'];

function buscar(){
  arrayOne.forEach(function(valor){
     const teste1 = document.getElementById('valorInput').value;       
      if(teste1 === valor){
        alert (true)
      } else {
        alert(false)
      }
  })  
}
<html>
  <body>
    <input id='valorInput'/> 
    <button onClick='buscar()'> Buscar </button>
    
    <h1 id='resultado'> Resultado </h1>
  </body>
</html>

I wanted to know how I do so that when I type the letter 'a' it returns true in the words that exist the letter 'a'?

Someone could help me ?

  • This seems to me an XY problem. If the idea is to find the names that correspond to what the user wrote the best is to use filter with const nomesFiltrados = arrayOne.filter(nome=>nome.indexOf(teste1) !== -1);

3 answers

1


To know if an element exists within an array or word, you can use the function indexOf() as follows:

var array = [2, 5, 9];
var index = array.indexOf(5);

If the value of the index variable is negative, it means that the element does not exist within (a) array/word.

  • Good afternoon Paul, thank you for answering. But if I want to know if there is a letter inside a given word of the array, I can use the index?

  • As you are already traversing each element of the array in foreach in if you can put valor.indexOf(teste1) < 0, where value is the element of the array being evaluated at the moment and the teste1 which has been typed.

  • Thank you very much. It worked. Could you explain something to me? ;valor.indexOf(teste1) < 0, means that the index of the.indexof value will be the test1 ?

  • The function returns an integer, value that is the position, then you can put in a variable, done this example I gave on the array, then if you do not find it retouches -1, so this validation of < 0.

1

The correct way is to use indexOf about the value of each item of the array, represented by the parameter valor in the forEach:

const arrayOne = ['jean','geleia','gean','ea games', 'e1'];

function buscar(){
  arrayOne.forEach(function(valor){
     const teste1 = document.getElementById('valorInput').value;       
      if(valor.indexOf(teste1) !== -1){
        console.log (true)
      } else {
        console.log (false)
      }
  })  
}
<input id='valorInput'/> 
<button onClick='buscar()'> Buscar </button>

<h1 id='resultado'> Resultado </h1>

0

You can also use the includes:

var s = 'an';
arrayOne.filter(x => x.includes(s)); // ["jean", "gean"]

Browser other questions tagged

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