How to check if an array contains a value in JavaScript?
Most of the scripting language has an in_array method to check an item exists inside an array or not. In JavaScript, it is a little different compare to other scripting languages. Until ECMAScript 7, there was no standard method to check this.
The modern JavaScript ECMAScript 7 introduces Array#includes for checking that. Before introducing Array#includes, JavaScript quite a few ways to do in_array check. In this article, we tried to compiles most of the ways to check an item exists inside an array or not.
Using Array#includes:
ECMAScript 7 introduces Array#includes, it checks an item is included inside an array or not. It is widely supported by all browsers except IE:
// Approach #1: console.log(['BMW', 'Toyota', 'Audi'].includes('BMW')); // true
Using Array#indexOf:
Array#indexOf is quite an old array method that we can use to checks an item is included inside an array or not. It is widely supported by all browsers except IE8:
// Approach #2: console.log(['BMW', 'Toyota', 'Audi'].indexOf('Audi') >= 0); // true
Using Array#lastIndexOf:
Array#lastIndexOf can be used to checks an item is included inside an array or not.
// Approach #3: console.log(['BMW', 'Toyota', 'Audi'].lastIndexOf('Audi') >= 0); // true
Using Array#some:
Array#some can be used to checks an item is included inside an array or not. It is widely supported by all browsers:
// Approach #4: console.log(['BMW', 'Toyota', 'Audi'].some(item => item === 'Audi')); // true
Using Array#filter:
Array#filter can be used to checks an item is included inside an array or not. It is widely supported by all browsers:
// Approach #5: console.log(['BMW', 'Toyota', 'Audi'].filter(item => item === 'Audi').length > 0); // true
Using Array#find:
Array#find can be used to checks an item is included inside an array or not.
// Approach #6: console.log(!!['BMW', 'Toyota', 'Audi'].find(item => item === 'Audi')); // true console.log(Boolean(['BMW', 'Toyota', 'Audi'].find(item => item === 'Audi'))); // true
Using Array#findIndex:
Array#findIndex can be used to checks an item is included inside an array or not.
// Approach #7: console.log(['BMW', 'Toyota', 'Audi'].findIndex(item => item === 'Audi') > -1); // true