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;
}
user1646528
  • 437
  • 2
  • 7
  • 15

4 Answers4

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
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;
};
Robin van Baalen
  • 3,632
  • 2
  • 21
  • 35
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');
}
Jitu Raiyan
  • 498
  • 6
  • 13
-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/

brroshan
  • 1,640
  • 17
  • 19
  • `Array.prototype.find` is an actual thing in future ECMAScript. I don't recommend naming the function that. – Mulan May 29 '15 at 23:05
  • It's right around the corner (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find); Firefox and Safari already have it implemented. – Mulan May 30 '15 at 18:19
  • Thanks for the info :) I didn't know – brroshan May 30 '15 at 20:41