How to Check if Array includes Value in JavaScript
When you have an array, you might want to check if a specific value is included in the array.
Thankfully, JavaScript has many built-in methods that can help you with this.
In this post, we'll learn how to check if a value is included in an array.
Using the includes method
One way to check if a value is included in an array is to use the includes
method.
This method returns true
if the value is included in the array, and false
if it isn't, which is exactly what we want.
JAVASCRIPTconst value = "foo";
const array = ["foo", "bar", "baz"];
const included = array.includes(value);
console.log(included);
BASHtrue
Using the indexOf method
The indexOf
method will return the index of the value in the array, or -1
if the value was not detected.
This makes it easy to use it to check if the value is included in the array.
JAVASCRIPTconst value = "foo";
const array = ["foo", "bar", "baz"];
const included = array.indexOf(value) > -1;
console.log(included);
BASHtrue
Using the some method
The some
method is an array method that runs a function on each element of the array, and returns true
if the function returns true
for any of the elements.
Here's an example:
JAVASCRIPTconst value = "foo";
const array = ["foo", "bar", "baz"];
const included = array.some(element => element === value);
console.log(included);
BASHtrue
This one is particularly useful when searching for objects:
JAVASCRIPTconst array = [{ foo: "baz" }, { foo: "bar" }];
const included = array.some(element => element.foo === "bar");
console.log(included);
BASHtrue
Using the some
method, we were able to check if an object had a foo
value equal to bar
.
Conclusion
In this post, we looked at three different ways that you can check if an array includes a specific value.
You can use the includes
method, the indexOf
method, or the some
method, depending on your use case.
Hope this was helpful and thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Getting Started with React