. Advertisement .
..3..
. Advertisement .
..4..
Are you trying to check if an array doesn’t contain values in JavaScript? Don’t worry; you are at the right place. This guide will show you several methods to perform this task. Let’s check it out to know more about these approaches.
Check If An Array Doesn’t Contain Values Utilizing includes()
To check whether or not an array doesn’t contain values, utilize the method includes(). It will check to see if a particular value is present in an array’s entries and returns true or false depending on the result.
Here is the code we use.
includes(searchElement)
includes(searchElement, fromIndex)
In this code, searchElement is the value that you want to search. Meanwhile, the fromIndex is the starting point for the searchElement operation within the array. Notice that the includes() method is case-sensitive when you compare characters and strings.
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, 3].includes(3, 3) // false
[1, 2, 3].includes(3, -1) // true
[1, 2, NaN].includes(NaN) // true
["1", "2", "3"].includes(3) // false
Check If An Array Doesn’t Contain Values Utilizing array.includes()
You can utilize array.includes() to check whether an array includes a primitive value. If it does, you will receive the true value. Otherwise, it returns false.
Below is an example of using the method array.includes().
var arr = [1, 2, 3, 4, 5];
var value = 5;
var isFound = arr.includes(value);
console.log(isFound);
/*
Output: true
*/
In case you need to ignore letter cases when performing the check process, follow the following step.
- First, give back a brand-new array with all of the entries in lowercase utilizing the toLocaleLowerCase() and map() methods.
- Next, utilize the method includes() to check.
You can see the above steps employed in the following sample.
const colors = ['Red', 'GREEN', 'Blue'];
const result = colors.map(e => e.toLocaleLowerCase())
.includes('green');
console.log(result); // true
As you can see, the array colors does not include green but rather GREEN value.
Here, the method map() first lowercases each element of the array colors before returning a different array. After that, the method includes() gives back the value true since the array includes the green element.
The Bottom Line
Now you know how to correctly check if an array doesn’t contain values in JavaScript. Hopefully, you find our guide helpful and easy to follow. Keep practicing, and you will be adept at using these methods in no time.Suppose you want to learn more JavaScript-related skills; check out our site. We provide many tutorials that can help you solve any problem you may have, such as adding class to clicked element or calculating percentage between two numbers.
Leave a comment