How to check each character in an array? JavaScript

0

Person, I have 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 that, when I type the letter 'a' it would return true in the words that exist the letter 'a'?

Could someone help me?

    
asked by anonymous 25.02.2018 / 17:57

3 answers

1

To find out if an element exists within an array or word, you can use the indexOf() following form:

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 the array / word.

    
25.02.2018 / 18:25
1

The correct way is to use indexOf on the value of each item in the array, represented by the parameter valor in 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>
    
25.02.2018 / 20:45
0

You can also use includes :

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