Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array search

Tags:

javascript

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;
}
like image 586
user1646528 Avatar asked Nov 21 '25 19:11

user1646528


1 Answers

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.

like image 151
Bergi Avatar answered Nov 24 '25 07:11

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!