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

      

+3


source to share


4 answers


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.

+5


source


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

      

+1


source


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

Run codeHide result


+1


source


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/

-1


source







All Articles