JavaScript check if a value is in the array using check-more-types library
In this JavaScript tutorial we learn how to check whether a given item is in the array or not using the check-more-types library.
Create the sample project
Firstly we create an empty project with the following command.
mkdir sample-project
cd sample-project
npm init -y
And install the check-more-types module using the following command.
npm install check-more-types --save
How to check a value is in the array
In this section we show you how to use the check-more-types library oneOf() method to check if a given value is in the array or not.
In the sample-project directory create a new file named check-one-of.js as below.
check-one-of.js
var check = require('check-more-types');
var languages = ['javascript', 'python', 'java', 'c'];
console.log(check.oneOf(languages, 'java'));
console.log(check.oneOf(languages, 'go'));
Run the check-one-of.js file using the following command.
node check-one-of.js
true
false
More examples of how to use the check.oneOf() method
check-one-of-example.js
var check = require('check-more-types');
var colors = ['red', 'green', 'blue', 'black'];
var color1 = 'blue';
var color2 = 'white';
if(check.oneOf(colors, color1)) {
console.log(color1 + ' value in the array.');
} else {
console.log(color1 + ' value does not existed in the array.');
}
if(check.oneOf(colors, color2)) {
console.log(color2 + ' value in the array.');
} else {
console.log(color2 + ' value does not existed in the array.');
}
Run the check-one-of-example.js file using the following command.
node check-one-of-example.js
blue value in the array.
white value does not existed in the array.
Happy Coding 😊