2

Using JavaScript or jQuery, I want to check through an array to make sure all items have a certain value. So for example, if I am checking for "active" in the following arrays, I want:

["active"] => true
["active", "active", "active"] => true
["active", "pending", "active", "active"] => false
["pending"] => false

What's the simplest way to accomplish this?

1
  • Loop through the array and compare each value to the first (zeroth) value. If they're different, the test is false. Commented Nov 3, 2015 at 21:34

1 Answer 1

7

You can use the JS Array function called every:

array.every(function(x) { return x == "active"; });

This will return true only if every element in array equals active.

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

2 Comments

Just make sure this is Compatible with what you are developing for.
array.every is implemented in most modern browsers and IE9+. Underscorejs is useful if you need to support IE7+. If you want to avoid all libraries go with @Blazemonger 's suggestion.

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.