Javascript array search
What is the best way to find a javascript array to write? All elements will be strings.
Is it easy with lastIndexOf? 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;
}
Is it easy with lastIndexOf?
Yes. However, I would use an even simpler indexOf()
one if you don't need to explicitly look back (which you don't if you are testing for "not contain "). Also note that these methods have been standardized in ES5 and should be customizable in older browsers that don't natively support them.
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;
};
You can try building a javascript array method find
. This is 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');
}
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/