I have lists of students. In a list, some students can be active, and others can be inactive.
var allActive = [{id: 1, active: true}, {id: 2, active: true}, , {id: 3, active: true}];
var someNot = [{id: 4, active: true}, {id: 5, active: true}, , {id: 6, active: false}];
I want to check that a list has all students active. The easy way is just to use a for loop
for(var index = 0, student; student = array[index]; index++){
if(stduent.active){
return false;
}
}
However, I do not want to create an additional piece of code like this. I want to use a quick way like forEach to check whether an array has all elements active. What would be a quick way to do it using some of the built-in array functions?
You can use the method every to do so. Here is an example
var allActive = [{id: 1, active: true}, {id: 2, active: true}, , {id: 3, active: true}];
var someNot = [{id: 4, active: true}, {id: 5, active: true}, , {id: 6, active: false}];
console.log(allActive.every(entry=>entry.active)); // expected output: true
console.log(someNot.every(entry=>entry.active)); // expected output: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With