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> <% } %> <% }); %>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With