freeCodeCamp Algorithm Challenge Guide: Everything Be True

freeCodeCamp Algorithm Challenge Guide: Everything Be True
0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: 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

:speech_balloon: Hint: 1

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

try to solve the problem now

:speech_balloon: Hint: 2

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

try to solve the problem now

:speech_balloon: Hint: 3

try to solve the problem now

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

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solutions ahead!

:beginner: Basic Code Solution:

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

:rocket: Run Code

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

:sunflower: Intermediate Code Solution:

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

:rocket: Run Code

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

:rotating_light: Advanced Code Solution:


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

:rocket: Run Code

Code Explanation:

  • For every object in the collection array, check the truthiness of object’s property passed in pre parameter
  • Array#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

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


#2

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;
}


#3

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

#4

#5

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

#8

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?


#9

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


#10

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.).


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

#13

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.


#14
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.


#15

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;
}

#16

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

#17
function truthCheck(collection, pre) {
  return !collection.some(function(i){
    return !(i[pre]);
  });
}

#18
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.


#19

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;
  
}

#20

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;
}

#21
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;
}

#22

I like this. So precise!