Traverse numerous arrays in JavaScript

I am attempting to search through three separate arrays of strings using Javascript. The goal is to find a user-inputted name and determine in which array it is located.

Here is an example of what I am trying to achieve: HTML

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

const form = document.querySelector('form');
const btnName = document.querySelector('#name');
let response = document.querySelector('#response');

function search() {

  response.innerText = '';
  let name = btnName.value.trim();

  for (i = 0; i < mods.length; i++) {
    if (name == mods[i]) {
      response.innerText += `${name} is a moderator`;
      break;
    } else if (i == users.length - 1) {
      for (i = 0; i < admins.length; i++) {
        if (name == admins[i]) {
          response.innerText += `${name} is an admin`;
          break;
        } else if (i == users.length - 1) {
          for (i = 0; i < users.length; i++) {
            if (name == users[i]) {
              response.innerText += `${name} is a registered user`;
              break;
            } else if (i == users.length - 1) {
              response.innerText += `${name} is NOT registered`;
              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>

Unfortunately, this code is not functioning as intended and is causing the browser to freeze. I suspect I have created an infinite loop somewhere... any suggestions? Thank you.

Big thanks to everyone for their helpful responses.

Answer №1

Give this a try!

let users = ['luigi', 'mario', 'peach'];
let admins = ['bowser', 'toad', 'yoshi'];
let mods = ['donkey kong', 'wario', 'waluigi'];

const form = document.querySelector('form');
const btnName = document.querySelector('#name');
let response = document.querySelector('#response');

function search() {

  let searchName = btnName.value;
  response.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">Enter a name</label>
  <input id="name" type="text" name="text" required/>
  <input type="button" onClick="search()" value="search">
  <label id="response"></label>
</form>

Answer №2

Utilizing User Object.entries, Locate, and Includes Functions

let users = ["alice", "bob", "charlie"];
let admins = ["dave", "eve", "frank"];
let mods = ["grace", "hank", "irene"];

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("hank");
const row = data[key];

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

Answer №3

If you want to check if an element exists in an array, you can use the includes method provided by 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} is NOT registered`;
  }
}


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue's v-for directive: Populate HTML dynamically with an event handler (@change) from an array within a component template

This is the setup I am currently using: HTML <question v-for="question in questions" v-bind:id="question.id" v-bind:title="question.title" v-bind:statement="question.statement" v-bind:interaction="question.interaction" @onchange-vg=" ...

Secure user verification using session variable in the Express framework with NodeJs

Is it safe to use session variables for login persistence in the backend? What are the security implications and alternatives to consider? Technology Stack: Express (NodeJs) on the backend, MaterialUI (React) on the frontend I am seeking a straightforwa ...

Difficulty encountered in closing dialog box upon clicking NavLink in React

Currently, I am developing a React application and have integrated a dialog box using the Material-UI library's Dialog component. Inside this dialog box, there is a navigation menu that I would like to close when a user clicks on one of the navigation ...

Bringing in an SVG file as a React component

When importing an SVG into React as a Component, I am facing an issue where the CSS classes are wrapped in style tags, causing an error upon import. Removing the CSS from the style tags allows the SVG to load, but it loses its additional styling. I want t ...

Creating a paired array - array_combine() requires the first parameter to be an array, but a string was provided

I'm attempting to create an associative array with the first element representing the headers. Starting with this array: Array ( [0] => Name,Phone number [1] => John,555666123 [2] => Bobby McQueen, 556699887 ) I want to transfo ...

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

Using an ng-repeat directive alongside an if condition in Angular

My website contains a vast array of 30 articles, previously represented by around 300 lines of HTML code, but now condensed to just 10 lines with angularjs. However, certain articles hold special significance and require specific display criteria. Check ou ...

Avoid using sleep statements in Webdriverjs to prevent stale element reference issues

I've come across a block of code that utilizes action sequences to execute the following steps: click on a link that directs to a specific page wait for an input field to become visible on the page click on the input field clear any existing text in ...

Retrieving a specific item from a sql-array using jOOQ

How do I retrieve an item from an array in JOOQ similar to this SQL query? SELECT (ARRAY_AGG(id))[1] FROM entities; Is there a way to achieve this using JOOQ? dsl().select(arrayAgg(ENTITIES.ID).get(1)).from(ENTITIES).fetch(); Alternatively, can I acces ...

The determination of the volume value was impossible using only the values from the object nested within an array

I am currently developing a react app that includes a button labeled Add to create a new calculation. Each calculation consists of two input fields for thickness and surface, as well as an output field for Volume. There is also a button labelled "X" to rem ...

Markers on Google Maps are failing to display when the locations are retrieved from a database

I am currently incorporating Google Maps API into my website using Node.js and mongodb. My Node.js express app fetches locations from mongodb, and I have successfully set up the map on my website. However, I am encountering an issue where only the hardcode ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

Reviewing the element names in a jQuery-selected array of objects

I'm new to javascript and the jquery library and I need to work with an array of input fields that have specific names for validation. Each input field is named NS[0], NS[1], etc., and the total number of these fields is generated dynamically in the c ...

Different ways to categorize and tally a collection of objects

I'm having trouble reshaping my data in order to create a stacked bar graph. The data from the backend is structured like this: [ {date: 'January', category: 'A'}, {date: 'January', category: 'B'}, ...

What is the most effective way to retrieve 'this' within an object method that is being used as a callback function?

I am currently working on a word game project to enhance my understanding of JavaScript, especially since I am new to it. To facilitate user interaction, I am utilizing the NPM package prompt (https://www.npmjs.com/package/prompt). Coming from an OOP back ...

What is the best way to iterate through a series of dataframes and perform operations using a for loop?

I've encountered a common issue and I'll use the Titanic dataset to illustrate. In order to perform operations on both the train and test sets simultaneously, I merged them together: combined = [train_df, test_df] In addition, I streamlined the ...

Troubleshooting Date Problems in Angular

When using the HTML5 date picker, I have encountered an issue where after choosing a date, the ng-model displays an older date instead of the current one selected. <input type="date" ng-model="dateModel" /> For example, when selecting the current d ...

Having issues with unchecking checkboxes in ReactJS

I created a task management app and I thought of improving it by displaying all completed tasks when the "Show completed tasks" box is checked. https://i.stack.imgur.com/RkXsw.png The issue I'm facing is that while checking "Show completed tasks ...

Leveraging php arrays for database interrogation

I am attempting to query a MySQL database using values passed in an array. The issue I'm facing is that the first element produces two results instead of one. Below is the code snippet and the corresponding results. $common = array_intersect($ingredi ...

Encountering a problem with parsing a JSON object using the .map

After receiving this JSON response, my main goal is to extract the value located in the identifier. By utilizing console.log, I am able to analyze the structure of the object: Object {rows: Array[33], time: 0.015, fields: Object, total_rows: 33} fields: O ...