bluehost-banner

How to Check if an Array Contains a Value in Javascript

In this tutorial, you’ll learn how to check if an array contains a value in JavaScript.


So, let get started...


1) Check if an array contains a string or number

To check if an array contains a string or number value, you can use the array method like array.includes()


const fruit= ['apple', 'banana', 'avocado'];
const result = fruit.includes('banana');

console.log(result); // true


Note: Includes is case sensitive


2)Using Some Method


The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.


const array = ['Sam', 'John', 'Alex'];


array.some(name => name === 'John');//true



 Some() is ideal for an array of objects.

const array = [{ name: 'Sam' }, { name: 'Alex' }];


array.some(code => code.name === 'Alex'); // true

array.some(code => code.name === 'John'); // false