Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast elements validation in an array

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?

like image 792
Pual Avatar asked Jun 18 '26 02:06

Pual


1 Answers

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
like image 85
orabis Avatar answered Jun 20 '26 15:06

orabis