Reputation: 267
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);
}
Upvotes: 1
Views: 218
Reputation: 13544
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/
Upvotes: 3
Reputation: 925
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/
Upvotes: 1
Reputation: 3850
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);
}
Upvotes: 2
Reputation: 894
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.
Upvotes: 1