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 Svelte
Getting Started with Electron
How to deploy a .NET app using Docker
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a Deno app using Docker
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Setting Up Stylus CSS Preprocessor
Using Axios to Pull Data from a REST API
