1

I am searching for an value from an array in javascript and this is my code.

HTML

<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>

Javascript

let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");

chkbutt.addEventListener("click", arraycheck);

function arraycheck () {
 for(i=0; i<arr.length; i++) {
   if(txtval.value==arr[i]) {
     alert("match found for " + txtval.value)
     }
  else {
   alert("its not there")
    }
 }
}

At the moment, I keep getting alert saying "its not there" when I enter "dog". It prints "its not there" twice and then prints "match found for dog". I would like the alert to show only if the word does not exist in the array. I know it is doing this because I have the if statement in the for loop and each time if the index of the array does not match, it shows the alert. But how do I do it?

5 Answers 5

3

You're alerting on every pass of the loop. Instead, use a flag and alert at the end:

function arraycheck () {
    var found = false; // *** The flag
    for (var i=0; !found && i<arr.length; i++) {
//                ^^^^^^^^^---- *** Stop looping if we find it
        if (txtval.value==arr[i]) {
            found = true; // *** Set the flag, it was found
        }
    }
    if (found) {
        alert("match found for " + txtval.value);
    } else {
        alert("its not there");
    }
}

or we could just use the result of the == directly:

function arraycheck () {
    var found = false; // *** The flag
    for (var i=0; !found && i<arr.length; i++) {
//                ^^^^^^^^^---- *** Stop looping if we find it
        found = txtval.value==arr[i]; // *** Set the flag if it was found
    }
    if (found) {
        alert("match found for " + txtval.value);
    } else {
        alert("its not there");
    }
}

(Side note: Unless you're declaring i somewhere you haven't shown, your code is falling prey to The Horror of Implicit Globals [that's a post on my anemic little blog]. Declare your variables. I've added declarations for i in the examples above.)


However, there's already a function for that (two, in fact): includes (on newer JavaScript engines) and indexOf (on older ones):

function arrayCheck() {
    var found = arr.includes(txtval.value); // <===
    if (found) {
        alert("match found for " + txtval.value)
    } else {
        alert("its not there")
    }
}

or the found part of that on older browsers using indexOf:

var found = arr.indexOf(txtval.value) != -1;

In a comment you asked:

I was wondering if you could also stop the loop in my code using "return"?

Yes, that's yet another way to do it in this specific case, since exiting the function (with return) exits the loop:

function arraycheck () {
    for (var i=0; i<arr.length; i++) {
        if (txtval.value==arr[i]) {
            alert("match found for " + txtval.value);
            return;
        }
    }
    alert("its not there");
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much. So many different ways to do things. I was wondering if you could also stop the loop in my code using "return"?
@craftdeer: Yes, in that specific case, using return in the loop would exit the function (and so naturally would exit the loop). So that's yet another option for you, I've added an example of it at the end above.
Awesome. Thank you everybody. I have learned a lot and need to learn a lot more. Happy New Year.
2

You can simplify using indexOf method,

if(arr.indexOf(txtval.value) > -1)

DEMO

let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");

chkbutt.addEventListener("click", arraycheck); 

function arraycheck () {
if(arr.indexOf(txtval.value) > -1)
  {
   alert("match found");
  }
  else {
   alert("its not there");
    }
 }
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>

Comments

1

Try the following with Array's includes() in a more simpler and cleaner way:

let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");

chkbutt.addEventListener("click", arraycheck);

function arraycheck () {
  if(arr.includes(txtval.value)){
    alert("match found for " + txtval.value)
  }
  else{
    alert("its not there")
  }
}
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>

Comments

1

Create a variable that will turn to true when a match is found. Then if after the loop the variable is still false, then no match has been found.

Or better yet, use lodash filter. It simplifies the looping process.

Comments

1

You can try to find the index of your txtval.value in the array by using JavaScript Array indexOf() method.

It takes a input value and output the index number of that value in the Array if the value exists.

As javascript array index starts from 0, so if the value exists, the method will return integer(index in the array) value that is greater than -1.

So, in your case,

function arraycheck () {
    var index = arr.indexOf(txtval.value);
    if(index > -1){
        //alert for found match
    }else{
        //alert for no match found
    }
}

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.