'Check if all values in my array equals specific text
I'm new to javascript. I created the following code to check if a specific value exists in an array and then show text based on whether the value exists or not:
// Get my div
ar mydiv = document.querySelector("#mydiv");
// Create Array
var mylist = Array.from(document.getElementsByClassName('myitem'), e => e.innerText)
// Check if value exist
myanswer = mylist.includes("None");
// Output Text
if (myanswer == true) {
mydiv.textContent = "True in list";
} else {
mydiv.textContent = "False in list";
}
It works well, but now I want to change it so that it checks weather ALL values in my array equals "None".
I changed the following line:
myanswer = mylist.includes("None");
To be this instead:
myanswer = mylist.every.equals("None");
This doesn't work though, so how is the best way to go about doing this?
Solution 1:[1]
In your case, MyList.every is a function not a single element.
What you want instead is checking if every element is equals to None.
Then The good way of doing it is the following :
myList.every(elem => elem === 'None')
This will return true if all elems are equals to None, false otherwise
Here is a small example with an array of string where you want to check if every item is 'None'
const arr1 = ['None','None','None','None','Not None']
const arr2 = ['None','None','None','None','None']
console.log(arr1.every(elem => elem === 'None'))
console.log(arr2.every(elem => elem === 'None'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cristian Traìna |
