The JavaScript array every() method checks whether all the given elements in an array are satisfying the provided condition. It returns true when each given array element satisfying the condition otherwise false.
JavaScript array every method tests whether all the elements in an array passes the test implemented by the provided function.
The every() method executes the function once for each element present in the array:
array.every(function(currentValue, index, arr), thisValue)
Check if all the answer values in the array are the same:
<script>
var survey = [
{ name: "Steve", answer: "Yes"},
{ name: "Jessica", answer: "Yes"},
{ name: "Peter", answer: "Yes"},
{ name: "Elaine", answer: "No"}
];
function isSameAnswer(el, index, arr) {
if (index === 0){
return true;
} else {
return (el.answer === arr[index - 1].answer);
}
}
function myFunction() {
document.getElementById("demo").innerHTML = survey.every(isSameAnswer);
}
</script>