1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 should be inArray() but otherwise yes, that's what I would use
@BrokenGlass - Thanks for reminding me, I didn't notice that :)
2
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.

Comments

Your Answer

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.