0

I am going through this challenge on FCC and I am literally half way there!

Check if the predicate (second argument) is truthy on all elements of a collection (first argument).

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

  for(var i = 0; i < collection.length; i++){
    var arr = collection[i];
    for(pre in arr){
      if (isNaN(arr[pre]) ){
        pre = false;
        return pre;
      } else if (arr[pre]){
        pre = true;
        return pre;
      }
    }
  }
}

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

In the introduction I said I was half way there. That's because when I evaluate the truthy values first:

if (arr[pre]){
  pre = true;
  return pre;
}

all the 'truthy' tests pass.

So I suppose I should be evaluated for 'truthtiness' in a different way? I say this because my code as is gets all the 'falsey' values to pass...

Thanks all!

fredmaggiowski
  • 2,232
  • 3
  • 25
  • 44
Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141
  • 1
    The truth will set you free – Tyler Apr 11 '16 at 18:19
  • 2
    start by not using `isNaN` it isn't doing what you think it is. `NaN` is falsy anyway. Not to mention the fact I don't see any falsey values in your array at all... – Jared Smith Apr 11 '16 at 18:21
  • Perhaps remove `for(pre in arr)` since `pre` is already specified as an argument to the function. It will return true for the first field, not for the given value of `pre`. – Kenney Apr 11 '16 at 18:23
  • I take my statement back; that question is quite misleading, and uses the word `predicate` to mean something that it doesn't. – Pointy Apr 11 '16 at 18:23
  • 1
    You're looking for `arr.every(o => o[pre])` (though "predicate" is a misnomer, it should be "property"). – Bergi Apr 11 '16 at 18:29

1 Answers1

2

It's false if falsey for any one of them, so test that. Then if none of them are falsey, return true.

function truthCheck(collection, pre) {
    for(var i = 0; i < collection.length; i++){
        if (!collection[i][pre]) { return false; }
    }
    return true;
}
Tyler
  • 11,272
  • 9
  • 65
  • 105