Everything be True

Everything be True
0

#1

Everything be true

https://www.freecodecamp.org/challenges/everything-be-true

Please help!

Surely the first test in the set of tests should equate to false no!?

truthCheck([{“user”: “Tinky-Winky”, “sex”: “male”}, {“user”: “Dipsy”, “sex”: “male”}, {“user”: “Laa-Laa”, “sex”: “female”}, {“user”: “Po”, “sex”: “female”}], “sex”)

We have 2 male and 2 female.

The challenge is to return true when all elements of the predicate (second argument) are true.

In this example the system is expecting true, but why!? Surely it should be false!?


#2

btw the link takes you to the challenge for reference.


#3

What is your reasoning behind a false answer?

[  
    {  
        “user”:“Tinky-Winky”,
        “sex”:“male”
    },
    {  
        “user”:“Dipsy”,
        “sex”:“male”
    },
    {  
        “user”:“Laa-Laa”,
        “sex”:“female”
    },
    {  
        “user”:“Po”,
        “sex”:“female”
    }
]

All objects in the array have a sex property, so it should be true.


#4

The predicate is “sex”, of which we have 2 males and 2 females. We should return true ifall elements are the same (all male or all female), which they are not, hence the answer should be false no?


#5

The challenge is to return true not if the predicate appears in each element but if the predicate is truthy on all elements.


#6

Since the elements of the array are objects and the predicate is a string the logical thing would be to chech if each object’s value evaluates to true or not. The exrcise doesn’t ask you to check if all values are equal.


#7

because in javascript, All values are truthy unless they are defined as falsy (i.e., except for false, 0, “”, null, undefined, and NaN).

So as long as it exists and don’t have the values false, 0, null, undefined, and NaN then it will be true
otherwise, if it has one of those values it will be false.

check this from MDN docs: https://developer.mozilla.org/en-US/docs/Glossary/Truthy


#9

Here is my solution. Use Boolean() to check truthy value, remember use bracket notation to access property of Object.

function truthCheck(collection, pre) {
  // Is everyone being true?
  let checkValue = collection.filter( item => {
  	if( item.hasOwnProperty( pre ) ) {
    	return Boolean( item[pre] );
    } else {
    	return false;
    }
  } ) ;
  return collection.length == checkValue.length ? true : false;
}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");

#10

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, please attempt to answer any question(s) posed by the OP instead of just posting a full working to a challenge.

It is much better if you can provide hints and suggestions to guide the OP in developing their own solution.

Thank you.