sk_225
sk_225

Reputation: 425

Underscore.js to check if element in array exists?

How do I check if the element in the array exists in underscore.js? For example, I have ['aaa', 'bbb', 'cfp', 'ddd'], and want to check to see if 'cfp' exists. If it does, I want to show some text. My code below doesn't work and I'm not sure why:

<% _.each(profile.designations, function(i) { %>                                                                                        
            <% if (typeOf profile.designations[i] == "cfp") { %>                                                                                         

            <div class="cfp-disclosure-text">                                                                                                           

              <p>Show this text if does exist</p>                                                                                                                                      

            </div>                                                                                                                                       

            <% } %>                                                                                                                                     

            <% }); %>

Upvotes: 22

Views: 43439

Answers (2)

Malay M
Malay M

Reputation: 1759

You can use ES6 array includes

const designations = ['aaa', 'bbb', 'cfp', 'ddd'];

const exists = fruits.includes('cfp');

console.log(exists);

or we can use directly

console.log(['aaa', 'bbb', 'cfp', 'ddd'].includes('cfp'))

Upvotes: 1

Mikhail Shabrikov
Mikhail Shabrikov

Reputation: 8509

Just use _.contains method:

http://underscorejs.org/#contains

console.log(_.contains(['aaa', 'bbb', 'cfp', 'ddd'], 'cfp'));
//=> true

console.log(_.contains(['aaa', 'bbb', 'cfp', 'ddd'], 'bar'));
//=> false
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Upvotes: 60

Related Questions