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!
Create an RSS Reader in Node
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
How to deploy a PHP app using Docker
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
Getting Started with Sass
Getting Started with Handlebars.js
Build a Real-Time Chat App with Node, Express, and Socket.io
Learn how to build a Slack Bot using Node.js
Creating a Twitter bot with Node.js
Getting Started with Vuex: Managing State in Vue
