freeCodeCamp Challenge Guide: Everything Be True

Everything Be True


Problem Explanation

The program needs to check if the second argument is a truthy element, and it must check this for each object in the first argument.

Relevant Links


Hints

Hint 1

Remember to iterate through the first argument to check each object.

Hint 2

Only if all of them are truthy will we return true, so make sure all of them check.

Hint 3

You could use loops or callback functions, there are multiple ways to solve this problem.


Solutions

Solution 1 (Click to Show/Hide)

Using for-in loop & hasOwnProperty

function truthCheck(collection, pre) {
  // Create a counter to check how many are true.
  var counter = 0;
  // Check for each object
  for (var c in collection) {
    // If it is has property and value is truthy
    if (collection[c].hasOwnProperty(pre) && Boolean(collection[c][pre])) {
      counter++;
    }
  }
  // Outside the loop, check to see if we got true for all of them and return true or false
  return counter == collection.length;
}

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

Code Explanation

  • First I create a counter to check how many cases are actually true.
  • Then check for each object if the value is truthy
  • Outside the loop, I check to see if the counter variable has the same value as the length of collection, if true then return true, otherwise, return false

Relevant Links

Solution 2 (Click to Show/Hide)

Using Array.every()

function truthCheck(collection, pre) {
  return collection.every(function(element) {
    return element.hasOwnProperty(pre) && Boolean(element[pre]);
  });
}

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

Code Explanation

  • Uses the native “every” method to test whether all elements in the array pass the test.
  • This link will help Array.prototype.every()

Relevant Links

Solution 3 (Click to Show/Hide)
function truthCheck(collection, pre) {
  // Is everyone being true?
  return collection.every(obj => obj[pre]);
}

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

Code Explanation

  • For every object in the collection array, check the truthiness of object’s property passed in pre parameter
  • Array.prototype.every method internally checks if the value returned from the callback is truthy.
  • Return true if it passes for every object. Otherwise, return false.

Relevant Links

10 Likes

It seems that you do not need to hasOwnProperty because if it does not have the property then it will return a falsey anyways. Thus my below solution worked. Thanks for the hard work friend. I like to read your solution after so I can see how to do it more efficiently/get exposed to more advanced code.

function truthCheck(collection, pre) {
for(i=0;i<collection.length;i++){
if(!collection[i][pre])
return false;
}
return true;
}

12 Likes

Another possible solution:

function truthCheck(collection, pre) {
  // Is everyone being true?
  return collection.every(function (element) {
    return element[pre];
  });
}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa"}, {"user": "Po", "sex": "female"}], "sex");
10 Likes
function truthCheck(collection, pre) {
var bool = false;  
  for (var each in collection) {
    if (collection[each][pre]) {
      bool=true;
    }
    else {
      return false;
    }
  }
 return bool;
}

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

Instead of using above code if you want to use this-
collection[i].pre
then it doesn’t pass all testcases.Can you please give any reason?

2 Likes

function truthCheck(collection, pre) {
return collection.reduce(function(acc,cur){ return Boolean(cur[pre] && acc); },true);
}

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

pre is a variable in this case, and you can’t use dot notation with variables. Writing collection[i].pre is like writing collection[i]['pre']. (Notice that in the latter “pre” is a string.).

6 Likes
function truthCheck(collection, pre) {
var res = collection.map(x => x[pre]);  
return res.every(p => p);
}

Can we please substitute the current “Basic Code Solution” with this one?

function truthCheck(collection, pre) {
  for (var obj = 0; obj < collection.length; obj++) {
    //the if statement using || could also be written as two if statements!
    //actually the first expression of the condition is not required
    if (!(pre in collection[obj]) || !collection[obj][pre]) {
      return false;
    }
  }
  return true;
}

Augorji already came up with this at the very beginning of this post and in terms of readability, cleanliness, and efficiency, it’s just better in my opinion. It immediately returns false, if the condition isn’t met and does not run until the very end, unlike the current solution.

5 Likes
function truthCheck(collection, pre) {
  for (var obj of arguments[0]){
    if (!obj[arguments[1]]){
      return false;
    }
  }
  return true;
}

Check out my code. Sweet and clean.

2 Likes

function truthCheck(collection, pre) {
  // Is everyone being true?
  
var rs = collection.reduce(function(a, b){
return Boolean(a) && Boolean(b[pre]) ? true :false;
}, true);

  return rs;
}

I completed mine using reduce.

function truthCheck(collection, pre) {
  // Is everyone being true?
  return collection.reduce(function(r,v){
    return r && Boolean(v[pre]);
  }, true);
}
function truthCheck(collection, pre) {
  return !collection.some(function(i){
    return !(i[pre]);
  });
}
function truthCheck(collection, pre) {
  for (var i = 0; i < collection.length; i++) {
    if (!Boolean(collection[i][pre])) {
      return false;
    }
  }
  return true;  
}

This is my solution. I feel like I am missing something here, though it passed all the tests. feedback would be really appreciated.

This was way easier than I thought :slight_smile:

function truthCheck(collection, pre) {
 
  for (var i = 0; i < collection.length; i++ ) {
    if (!collection[i][pre]) {
      return false;
    }
  }
  
  return true;
  
}
1 Like

Everyone else got these super short concise results… mine is a lot longer but it worked and Im proud of it (for now, in a couple months Im sure I will see this and cringe) anyway, here’s what I came up with.

function truthCheck(collection, pre) {
    // Is everyone being true?


    var colSize = Object.values(collection).length;
    var match = "";

    //find the matching key to find truthy value to compare
    for (i = 0; i < colSize; i++) {

        var keys = (Object.keys(collection[0])); // [ 'user', 'sex', 'age' ])
        if (keys[i] === pre) {
            match = i;
            console.log(match);
        }
    }

    //iterate through collection and if key value is false, all are not truthy!
    for (i = 0; i < colSize; i++) {

        var colValue = Object.values(collection[i]); // [ 'Tinky-Winky', 'male', 0 ]
        if (!colValue[match]) {
        	console.log(false);
        	return false;
        }
        console.log(true);
            
    }

return true;
}
1 Like
function truthCheck(collection, pre) {
  // Is everyone being true?
  var bool = collection.every(function(element,index,array)
{
    if(element.hasOwnProperty(pre)&&element[pre]!=false&&element[pre]!=0,element[pre]!=""&& element[pre]!=null&&element[pre]!=undefined&&!Number.isNaN(element[pre])){
     return true;
    }
    return false;
  }
);
  return bool;
}

I like this. So precise!