Reputation: 845
var testVar = [null, true, true, false, false];
//Paulpro's solution (not mine)
switch (testVar.indexOf( true )) {
case 1:
console.log('Im in the first group!');
break;
case 2:
console.log('Im in the second group!');
break;
case 3:
console.log('Im in the third group!');
break;
}
testVar is an array like this [null, true, true, false, false, false] for an employee in the first group (index 1 is true) AND second group, but not the third group.
Upvotes: 3
Views: 5344
Reputation: 141877
Find the position of true
in the groups array (using indexOf) and use that for your switch statement:
contacts.forEach(function(employee, index){
switch (employee.groups.indexOf( true )) {
case 1:
console.log('Im in the first group!');
break;
case 2:
console.log('Im in the second group!');
break;
}
});
If the user can be in multiple groups it's better to use a series of if statements:
contacts.forEach(function(employee, index){
if ( employee.groups[1] ) {
console.log('Im in the first group!');
}
if ( employee.groups[2] ) {
console.log('Im in the second group!');
}
});
Upvotes: 3