how to find if it contains text inside a javascript array

Asked

Viewed 363 times

2

I created two arrays, one with questions and the other with answers.

Follows the model.

perguntas[0] = "que sao dinossauros";
respostas[0] = ["Constituem um grupo de diversos animais membros do clado Dinosauria"];

perguntas[1] = "tipos de dinossauros que existiram";
respostas[1] = ["Terópodes, Saurópodes, Ceratopsídeos, Ornitópodes, Estegossauros, Anquilossauros,Paquicefalossauros"];

Well, I need to make sure that I find if certain text, is contained in that array, knowing in what position it found, so I can return a response.

I tried it this way.

 if( $.inArray(pergunta, perguntas[i]) !== -1 ){
                alert("encontrei");
            }else{
                alert("não encontrado");
            };

So it works, however I need to find which position was found, to send a respective return.

I created a repetition to be able to identify in which position it was found, but never finds the text.

for(var i = 0; i < perguntas.length; i++){

            if( $.inArray(pergunta, perguntas[i]) !== -1 ){
                alert("encontrei");
            }else{
                alert("não encontrado");
            };
        }

Thank you

  • You are looking for the question, in case, and need to know what is the index of this question in the list?

  • I forgot to put in the remark that the user who enters the question. Then let’s say that the guy type "Tiranosaurus", if he finds the content, I need to know in which information was found

  • Ok, so the user type in a word, you want to search what is the question that has this word and get the index of this in the list?

  • I want to check if the word is contained in the array. If it is, I need to know which part is in order to return the corresponding answer.

2 answers

2


To search for the question and display the answer, just use indexOf in the list of questions to get the position of the question in the list and display the answer used respostas[index]. Take the example:

// Objetos de manipulação do DOM -------------------------------------------------------
const lista    = document.getElementById("perguntas"),
      pergunta = document.getElementById("pergunta"),
      resposta = document.getElementById("resposta"),
      button   = document.getElementById("perguntar");
      
// Lista de perguntas e respostas ------------------------------------------------------
const perguntas = [],
      respostas = [];

// Adiciona-se as perguntas e respostas ------------------------------------------------
perguntas.push("O que são dinossauros?");
respostas.push("Constituem um grupo de diversos animais membros do clado Dinosauria");

perguntas.push("Quais os tipos de dinossauros que existiram?");
respostas.push("Terópodes, Saurópodes, Ceratopsídeos, Ornitópodes, Estegossauros, Anquilossauros,Paquicefalossauros");

perguntas.push("Onde é que eu tô? Será que tô na alagoinha?");
respostas.push("Não, você está no Stack Overflow em Português.");

// Exibe as perguntas para o usuário ---------------------------------------------------
// Não é necessário para a resolução da pergunta, mas ajuda o usuário.
for (let i in perguntas)
{
  let li = document.createElement("li");
  li.innerHTML = perguntas[i];
  
  li.onclick = function (event) {
    pergunta.value = perguntas[i];
  }
  
  lista.appendChild(li);
}

// Evento de click do botão ------------------------------------------------------------
button.onclick = function (event) {

  // Procura a pergunta na lista de perguntas:
  let index = perguntas.indexOf(pergunta.value);
  
  // Se encontrar, exibe a resposta, caso contrário exibe a mensagem de erro:
  resposta.innerHTML = (index >= 0) ? respostas[index] : "Pergunta não encontrada";
};
li {
  cursor: pointer;
}
<ul id="perguntas"></ul>

<input id="pergunta" type="text">
<button type="button" id="perguntar">Perguntar</button>

<div id="resposta"><div>

Show 2 more comments

1

You can scroll through the array of responses using forEach and save position when find:

var perguntas = [],
  respostas = [];
perguntas[0] = "que sao dinossauros";
respostas[0] = "Constituem um grupo de diversos animais membros do clado Dinosauria";

perguntas[1] = "tipos de dinossauros que existiram";
respostas[1] = "Terópodes, Saurópodes, Ceratopsídeos, Ornitópodes, Estegossauros, Anquilossauros,Paquicefalossauros";

var respondido = "Anquilossauros";
var idx;
respostas.forEach(function(item, i) {
  if (item.indexOf(respondido) > -1) 
    idx = i;
});

if (idx) {
  console.log('A resposta está na posição: ' + idx);
}

I exemplified an answer to the question types of dinosaurs that existed.

  • That’s not exactly what I need. Let’s say the guy asks. What kind of dinosaurs have there been? That’s the answer to the question[1]. Ai wanted to return him

  • So why the value of resposta[1] is an array?

  • only ta separated by commas, but not array, it is inside quotes

  • It starts with clasps

  • ignore it then

  • I just need to find out which position contains what the guy types in this array of questions

  • I edited the reply @gabrielfalieri

Show 2 more comments

Browser other questions tagged

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