Check if an array does not have certain value in JavaScript
In this tutorial, we are going to learn about how to check if an array does not contains particular value or not in JavaScript.
Consider, we have a following array in our JavaScript code.
const arr = [1, 44, 5, 77, 35]
Now, we need to check if an array doesn’t have certain value or not.
To check if an array doesn’t have certain value or not, we need to use the (!) not operator infront of includes() method call, so that it returns “true” if a value is not found in the array otherwise it returns true.
Here is an example:
const arr = [1, 44, 5, 77, 35];
const result = !arr.includes(100);
console.log(result);
Output:
True
In the code above, we have passed the value 100 to the negate includes() method.So that it checks whether the array doesn’t contains value 100 or not, if 100 is not there in the array it returns ‘true’ otherwise it returns false.
We can also count, how many times a button is clicked like this:
Here is an example:
const button = document.getElementbyId("btn");
let count = 0;
button.addEventListener("click", ()=>{
count = count + 1;
alert("button is clicked" + count);
})
We can also check if an object doesn’t contain in an array or not like this in the JavaScript:
const arr = [{id: 1}, {id: 2}, {id : 3}];
const notObject = arr.every(obj => obj.id !=5 ); // true