Ralph43
Ralph43

Reputation: 13

javascript validate value against array

I'm looking for a way to verify against an array. I'm lost in the array searching part.

I may get an array like this:

stream = ["apple","orange", "grape", "peach","strawberry","watermelon", "kiwi", "raspberry"];

But I only want :

selection = ["apple", "peach","strawberry","kiwi", "raspberry"];

How would I write a statement that would say: If something in this stream matches my selection, do something.

Upvotes: 1

Views: 2492

Answers (2)

Hallaghan
Hallaghan

Reputation: 1941

You must use the inArray command like this:

if($.inArray(ValueToCheck, YourArray) > -1) { alert("Value exists"); }

InArray will search your array for the value you asked for and return its index. If the value isn't present, it returns -1.

Upvotes: 3

jAndy
jAndy

Reputation: 236182

var stream    = ["apple","orange", "grape", "peach","strawberry","watermelon", "kiwi", "raspberry"],
    selection = ["apple", "peach","strawberry","kiwi", "raspberry"];

stream.forEach(function(elem) {
    if( selection.indexOf(elem) > -1 ) {
        // we have a match, do something.
    }
});

Note that Array.prototype.forEachhelp and .indexOf()help are part of Javascript 1.6 and may not be supported by any InternetExplorer < version 9. See MDC's documentation on alternative versions.

There are lots of other ways to accomplish the same thing (using a "normal" for-loop for instance) but I figured this is probably the best trade-of in performans vs. readability.

Anyway, all the used Javascript 1.6 functions are actually very trivial to write on your own.

jQuerys $.inArray()help will also use Array.prototype.indexOf() if it's supported by the browser.

Upvotes: 2

Related Questions