Hello !
Here’s my straight to the point and easy to understand solution. I’m glad others reached the same solution, that means I’m doing something right
function truthCheck(collection, pre) {
// Is everyone being true?
for (var i = 0; i < collection.length; i++) {
if(!collection[i][pre]) return false;
}
return true;
}
//Flawless victory!
truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
2 Likes
Hello @Venkateshwaran !
Well I’m no JS expert in here, but you solution is in principle like mine, and I think it can be described as follows:
In your for
loop you have the if
statement that checks on every object
from the collection array
that it has a property that’s truthy
or falsy
based on the second argument of the function, pre
. All that is evaluated in a Boolean
context and your condition was to check if the Boolean
is false
then return false
, and given that the two states are mutually exclusive, to return
true
in the all other situations.
You can easily leave out the Boolean
as is not really necessary and go for the direct and simplified form:
if(!collection[i][pre]) return false;
From my point of view I understood what’s happening in there, and hope my explanation was correct & helpful. You can check my solution down 4 rows from yours . It’s practically like yours.
Cheerio!
1 Like
function truthCheck(collection, pre) {
// Is everyone being true?
flag = true;
var x = collection.forEach(function(val){
if(Boolean(val[pre])===false) flag = false;
});
return flag;
}
how about this?
A solution i found earlier:
return collection.map(x => x[pre]).filter(Boolean).length === collection.length ? true : false;
what do you guys think? any feedback?
3 Likes