Javascript: Check If String In List

November 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)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.