Skip to content
the poor coder

javascript - Determine whether an array contains a value

Poor Man
Published
Reading time
2 min read

The easiest way to determine whether an array contains a value is to use the Array.prototype.includes() method. This method checks whether an array contains a certain element and returns true or false. For example, the following code will check whether the array arr contains the value 3:

Text

const arr = [1, 2, 3, 4, 5];
const containsThree = arr.includes(3);
console.log(containsThree); // true

There are also a few other ways to do this. For example, you can use the Array.prototype.indexOf() method, which returns the index of the first occurrence of a given element in the array. If the element is not found, the method returns -1. So if you want to check if an array contains a given value, you can check if the indexOf() result is not -1. For example:

Text

const arr = [1, 2, 3, 4, 5];
const indexOfThree = arr.indexOf(3);
const containsThree = indexOfThree !== -1;
console.log(containsThree); // true

Finally, you can also use the Array.prototype.some() method, which returns true if at least one element in the array passes the given test. For example:

Text

const arr = [1, 2, 3, 4, 5];
const containsThree = arr.some(el => el === 3);
console.log(containsThree); // true

If you want to check if an array contains multiple values, you can also use the Array.prototype.every() method, which returns true if every element in the array passes the given test. For example:

Text

const arr = [1, 2, 3, 4, 5];
const containsOneTwoThree = arr.every(el => [1, 2, 3].includes(el));
console.log(containsOneTwoThree); // true

As you can see, there are a few different ways to determine whether an array contains a value, and it's up to you to decide which one is the most appropriate for your use case.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC