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;
}
-
Do you need all occurrences? What doesn't work about lastIndexOf?Matt Zeunert– Matt Zeunert2013年02月05日 19:57:45 +00:00Commented Feb 5, 2013 at 19:57
4 Answers 4
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.
1 Comment
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;
};
Comments
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');
}
Comments
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.
3 Comments
Array.prototype.find is an actual thing in future ECMAScript. I don't recommend naming the function that.