Reputation: 437
Whats the best way to search a javascript array for an entry?? All the items will be strings.
Is it simply by using lastIndexOf? like so:
var list= [];
list.push("one");
list.push("two");
list.push("three");
if(list.lastIndexOf(someString) != -1)
{
alert("This is already present in list");
return;
}
Upvotes: 3
Views: 220
Reputation: 536
You can try the build in array method of javascript find
. It's the easiest way for your problem. Here is the code:
var list = [], input = "two";
list.push("one");
list.push("two");
list.push("three");
function match(element){
return element == input;
}
if(list.find(match)){
console.log('Match found');
}
Upvotes: 1
Reputation: 1650
var arr = ["one","two","three"];
Array.prototype.find = function(val){
for(var i = 0; i < this.length; i++) {
if(this[i] === val){
alert("found");
return;
}
}
alert("not found");
}
arr.find("two");
Should work in most older browsers.
https://jsfiddle.net/t73e24cp/
Upvotes: -1
Reputation: 3651
For older browser support, you should still use a loop:
function inArray(arrToSearch, value) {
for (var i=0; i < arrToSearch.length; i++) {
if (arrToSearch[i] === value) {
return true;
}
}
return false;
};
Upvotes: 1
Reputation: 665361
Is it simply by using lastIndexOf?
Yes. However, I'd use even simpler indexOf()
if you don't need to explicitly search backwards (which you don't if you test for "does not contain"). Also notice that these methods were standardized in ES5 and need to be shimmed in old browsers that do not support them natively.
Upvotes: 5