3

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;
}
asked Feb 5, 2013 at 19:56
1
  • Do you need all occurrences? What doesn't work about lastIndexOf? Commented Feb 5, 2013 at 19:57

4 Answers 4

5

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.

answered Feb 5, 2013 at 19:59
Sign up to request clarification or add additional context in comments.

1 Comment

@MikeCorcoran he specifically said it needs to be shimmed in older browsers.
1

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;
};
answered Feb 5, 2013 at 20:03

Comments

1

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');
}

answered Apr 9, 2017 at 20:01

Comments

-1
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/

answered May 29, 2015 at 22:58

3 Comments

Array.prototype.find is an actual thing in future ECMAScript. I don't recommend naming the function that.
It's right around the corner (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…); Firefox and Safari already have it implemented.
Thanks for the info :) I didn't know

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.