-1

I'm trying to make a search through three different arrays of strings in Javascript, looking for a name (submitted by user), and if this name is found, I have to return in which array it is located.

Something like that: HTML

let users = ['mario', 'gianni', 'pinotto'];
let admins = ['moana', 'cicciolina', 'selen'];
let mods = ['frodo', 'sam', 'bilbo'];

const form = document.querySelector('form');
const btnNome = document.querySelector('#nome');
let risp = document.querySelector('#risposta');

function search() {

  risp.innerText = '';
  let nome = btnNome.value.trim();

  for (i = 0; i < mods.length; i++) {
    if (nome == mods[i]) {
      risposta.innerText += `${nome} is a moderator`;
      break;
    } else if (i == users.length - 1) {
      for (i = 0; i < admins.length; i++) {
        if (nome == admins[i]) {
          risposta.innerText += `${nome} is an admin`;
          break;
        } else if (i == users.length - 1) {
          for (i = 0; i < users.length; i++) {
            if (nome == users[i]) {
              risposta.innerText += `${nome} is a registered user`;
              break;
            } else if (i == users.length - 1) {
              risposta.innerText += `${nome} NON è registrato`;
              break;
            }
          }
        }
      }
    }
  }
  form.reset();
};
<form>
  <label for="text">Insert name</label>
  <input id="name" type="text" name="text" required/>
  <input type="button" onClick="search()" value="search">
</form>

BUT it doesn't work, and freezes the browser. I think I have mistaken something creating a infinite loop... any ideas? thanks

THANK you everyone for your answers, which were all very useful.

5
  • 1
    Can you please fix the indentation. That's absolutely terrible to read and understand... Commented Mar 18, 2020 at 11:35
  • There is no element with id risposta. Also the variable is risp not risposta Commented Mar 18, 2020 at 11:37
  • You have to define a variable in JavaScript with var, let or const otherwise they are global. You should go with let in this case to get a writable variable with block scope. Commented Mar 18, 2020 at 11:39
  • Does this answer your question? Check if string inside an array javascript Commented Mar 18, 2020 at 11:45
  • Concat all the arrays into one and use some Commented Mar 18, 2020 at 12:04

3 Answers 3

0

Try this

let users = ['mario', 'gianni', 'pinotto'];
let admins = ['moana', 'cicciolina', 'selen'];
let mods = ['frodo', 'sam', 'bilbo'];

const form = document.querySelector('form');
const btnNome = document.querySelector('#nome');
let risp = document.querySelector('#risposta');

function search() {

  let searchName = btnNome.value;
  risp.innerHTML = 
    checkWithArray(searchName, 'user', users) +
    checkWithArray(searchName, 'admin', admins) +
    checkWithArray(searchName, 'mod', mods);
  console.log(searchName);

  form.reset();
};

function checkWithArray(searchName, title, arr) {
  if (arr.indexOf(searchName) > -1) {
    return `${searchName} is ${title}. `;
  }
  return '';
}
<form>
  <label for="text">Insert name</label>
  <input id="nome" type="text" name="text" required/>
  <input type="button" onClick="search()" value="search">
  <label id="risposta"></label>
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

Why should OP do this? What did you change?
I just refactor the code to be shorter. Hence less bug.
0

User Object.entries, find and includes methods

let users = ["mario", "gianni", "pinotto"];
let admins = ["moana", "cicciolina", "selen"];
let mods = ["frodo", "sam", "bilbo"];

const data = { users, admins, mods };

const search = str => {
  const found = Object.entries(data).find(([key, arr]) => arr.includes(str));
  return found ? found[0] : "";
};

const key = search("sam");
const row = data[key];

console.log(`sam found in ${key} and array is ${row}`);

Comments

0

You can use Array's includes method to find if element exist in an array:

let users = ["mario", "gianni", "pinotto"];
let admins = ["moana", "cicciolina", "selen"];
let mods = ["frodo", "sam", "bilbo"];

const form = document.querySelector("form");
const btnNome = document.querySelector("#nome");
let risp = document.querySelector("#risposta");

function search() {
  risp.innerText = "";
  let nome = btnNome.value.trim();

  checkWithArray(nome, "user", users);
  checkWithArray(nome, "admin", admins);
  checkWithArray(nome, "moderator", mods);

  form.reset();
}

function checkWithArray(searchName, title, arr) {
  const isFound = arr.includes(searchName);

  if (isFound) {
    let text;

    switch (title) {
      case "user":
        text = `${searchName} is a registered user`;
        break;
      case "admin":
        text = `${searchName} is an admin`;
        break;
      case "moderator":
        text = `${searchName} is a moderator`;
        break;
    }

    risp.innerText += text;
  } else {
    risp.innerText += `${searchName} NON è registrato`;
  }
}


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.