Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js to check if element in array exists?

Tags:

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>                                                                                                                                                     <% } %>                                                                                                                                                   <% }); %> 
like image 985
sk_225 Avatar asked Jul 16 '16 01:07

sk_225


1 Answers

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>
like image 62
Mikhail Shabrikov Avatar answered Sep 16 '22 14:09

Mikhail Shabrikov