Tips for retrieving array results from a loop and systematically inspecting each element

In this code snippet, I am attempting to retrieve results from an array and evaluate them one by one.

////////////////////////////////////////
/////////////// Code Issue ////////////////////////
///// The current implementation is not functioning properly, ///////
///// and lacks flexibility /////////////
////////////////////////////////////

var myA = ["said", "imad", "hassan", "bilal", "mohamed"];
var doc = document.getElementById('div1');
var inp = document.getElementById('input1');

function click1() {
    'use strict';

    var i = inp.value;

    if (i <= 0) {
    doc.innerHTML = 'Please enter a name';

    } else if (i === myA[0] || i === myA[1] ||
           i === myA[2] || i === myA[3] || i === myA[4]) {
    doc.innerHTML = i;

    } else {
    doc.innerHTML = 'Please enter a correct name';
    }
}


/////////////////////////////////////////////////////
////////////// Attempt to Improve Flexibility //////////////
///////// However, only the last index is being retrieved ////////////
/////////////////////////////////////////////////////


var myA = ["said", "imad", "hassan", "bilal", "mohamed"];
var index = myA[0];
// console.log(index);
var doc = document.getElementById('div1');
var inp = document.getElementById('input1');

function getId(a){
  var aL = a.length, index = a[0], x=0;

  for(x = 0; x < aL; x++ ){
  index = a[x];
  // console.log(index);
  }    
  return index;
}  
// console.log(getId(myA));

function click1() {
  'use strict';

  var i = inp.value;

  if (i <= 0) {
  doc.innerHTML = 'Please type name';

  } else if (i === getId(myA)) {
  doc.innerHTML = i;

  } else {
  doc.innerHTML = 'Please type in a correct name';
  }
}

Answer №1

How can you verify if a specific value exists within an array:

The latest approach (ES6):

if (myA.includes(inp.value)) {
  // The name is present in the array
}

Traditional method:

if (myA.indexOf(inp.value) > -1) {
  // The name is found in the array
}

Answer №2

The implementation of your getId() function needs some adjustments. Currently, it iterates over the myA array and always returns the last element "mohamed". To fix this, the function should take a value to compare, loop through the array, and return true if a match is found or false if not.

function getId(value) {
  for(var index = 0; index < myA.length; index++) {
    if(myA[index] === value) {
      return true;
    }
  }
  return false;
}

To use the corrected function:

if (getId(input)) {
   doc.innerHTML = input;

} else {
   doc.innerHTML = 'Please enter a valid name';
}

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

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Click event doesn't trigger the 'else if' statement in jQuery

Having trouble with a button click issue. In the following code, when the button is clicked, it checks if the text on the button is "day". If so, it changes the background-color of the body to red and updates the button text to "night". I am struggling wit ...

Capture an image of a webpage and print it out

I am currently in the process of designing a web page and one of the key features I need is a button that allows users to print a selected area. After conducting several searches, I came across html2canvas as a potential solution. I proceeded to install it ...

The skybox in Three.js appears to be malfunctioning following a camera rotation

Working with JavaScript, I am attempting to build a basic skybox inspired by this demo. Everything is going smoothly except for one issue - when I rotate the camera (using orbitControls.js) and the z value is not at its minimum, the textures start to glitc ...

Tips for extracting <span> element values from an array and saving them in a new array using Javascript

I have a list of countries with unique identifiers attached to them using a <span> element. Here is an example: var countryList = [ 'Asia <span class="hide">1234</span>', 'Ireland <span class="hide">65d ...

How to stop a component template in Angular from displaying both conditional statements simultaneously?

I want to prevent my component template from briefly displaying both conditional statements when the condition changes after the component has been initialized. My application receives a token, and depending on its validity, it shows the appropriate conte ...

Sorting Tables (Implementing ng-repeat and eliminating duplicate column names with ng-if)

I have a table with data displayed using ng-repeat and it is currently sorted properly. To view the initial setup, check out the first fiddle. http://jsfiddle.net/HB7LU/10201/ <tr ng-repeat="each in list | orderBy:predicate:reverse"> I am aiming t ...

Searching for a specific MongoDB document based on an element within an array

https://i.sstatic.net/1gv6N.png This individual's notes are stored in a database. I am attempting to retrieve only the notes marked with "activeFlag:1" for this specific user. Below is my code for the query object: findAccountObj = { _id: objectID( ...

Show the button when the mouse moves over the image

Here is the snippet of code I am working with: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <script src="Js/jquery.min.js"></script> <script type="text/javascript"> $(document).r ...

Update View Not Reflecting React State Increment

Here is the code snippet I am currently working with: class PickColor extends React.Component { constructor(props) { super(props); this.state = { active: 0 } this.setState = this.setState.bind(this); } ...

Unable to submit a fetch request

I've been searching for quite some time without finding any answers to this particular issue. The problem I'm facing is that when I attempt to send an asynchronous request to another web page, I'm not receiving any response. I suspect that t ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

Ways to prevent ERR_INSUFFICIENT_RESOURCES when making AJAX requests

It's been a while since I dabbled in JavaScript, so please be patient with me. I'm currently developing an application that generates reports on student data using PHP as the backend. Periodically, we need to refresh the database used for these ...

Add an element to an array at a designated position using a pipeline operation (aggregation or update) in MongoDB

After coming across another inquiry, I delved into the search for a standard method to add an element at a specific location within an array using a pipeline, but my quest turned up empty. Suppose my document structure resembles the following: [ { _i ...

Unlocking the Secrets: Retrieving Message Embeds Using Discord.js' Message ID

I've been working on creating an advanced suggestion command and here is the progress I've made with the code: if (command === 'accept') { try { const suggestionchan = bot.channels.cache.get('840493081659834403'); const a ...

Exploring the JSON Array in Angular5 with the power of ngFor

Currently, I am working on a project using Angular5 and encountering an issue with the *ngFor directive. The model class I have defined looks like this: export class FetchApi { value: Array<String>; api_status: string; api_version: string; d ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

"Stop" and "start" a loop in AngularJS

Feeling a bit lost on how to articulate this inquiry, or even where to start looking for answers. I have a dynamic photo/text feed populating an array, meaning my page is constantly being updated with new information. The influx of data is happening at a ...

Tips for using regular expressions to extract body content

I have this code saved in a variable. <html> <head> . . anything . . </head> <body anything=""> content </body> </html> or <html> <head& ...

Displaying array items with a one-second pause using the sleep() function

My goal is to print out each element of an array containing characters once every second. However, when I try to do this without adding a new line after each element, the code waits for 110 seconds before printing out the whole array at once. int i=0; whi ...