Javascript: Check If String In List

Nov 2, 2017
ES6: ['apple', 'orange', 'banana'].includes('banana')

It's simple using ES6 Javascript.

TIPS: you can use Babel (or use babel-loader with Webpack) for cross-browser support.

['apple', 'orange', 'banana'].includes('banana')

Using indexOf, but it doesn't work with IE8.

if (['apple', 'orange', 'banana'].indexOf(value) >= 0) {    // found}

To support IE8 as well, you could implement Mozilla's indexOf polyfill.

if (!Array.prototype.indexOf) {    // copy Mozilla's indexOf polyfill code here}

You can also use jQuery inArray.

jQuery.inArray(value, ['apple', 'orange', 'banana')

If you are using underscore or lodash.

_.indexOf['apple', 'orange', 'banana'], value)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.