Everything be True

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!?

btw the link takes you to the challenge for reference.

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.

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?

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

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.

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

1 Like

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");