1

I have a functions which asks the users to write their favorites animals ant then stores it in an array called animals.When a user executes the function I want to check if the animal he wants is inside the array and if yes to show the index of the animal(for example:The animal you entered is already in the array.Its index number is...).Any ideas?

var animals=[]
function anim(){
var ani=prompt("Give me an animal you like");
animals.push(ani);

}

4 Answers 4

3

You can iterate across the array and with regex to get accurate result regard less input case

 function searchArr(arr, q){      
      for (i = 0; i < arr.length; i++){
        patt = new RegExp(q,"i");
        if (patt.test(arr[i])) return i;
      }
      return false;
    }

Testing Code:

 animals = new Array('dog', 'cat', 'camel', 'deer');
    q = prompt("Enter Animal Name");
    r = searchArr(animals,q);
    alert(r)
    if (r || r ===0){
      alert("Animal found and its index " + r)
    }
    else{
      alert("Not found")
    }

Demo: http://jsbin.com/jolaqiduka/1/

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

Comments

2
var animals= new Array('dog');
var ani=prompt("Give me an animal you like");
if(animals.indexOf(ani) >= 0 ){
    alert(animals.indexOf(ani));


}else{
   animals.push(ani);
}

JsFillde Demo

1 Comment

As a side note, to support IE8<, you should use jQuery $.inArray() method instead: api.jquery.com/jquery.inarray or any Array.prototype.indexOf polyfill
1

you can find out if a value is inside of an array by using indexOf().

for example: animals.indexOf('dog');

this will return the index of the string 'dog'. if it doesn't exist, it will return a value of -1.

Comments

1

This this way

var animals=[]

function anim() {
   var ani = prompt("Give me an animal you like");

   // The function returns a position of an input element (in array) begins from the 0
   // or -1 if the element is not exists in the array
   if (animals.indexOf(ani) > -1)
       alert('Already in');
   else
       animals.push(ani);
}

Next fiddle may help: http://jsfiddle.net/8g5gpqx2/

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.