Tell us what’s happening:
Hi, as I was working through this challenge I tried using a for of loop since it looks at the values of arrays and such, but it would return undefined (I’m assuming this is because there are objects in the array). It worked with a for in loop but and I understand that a for in loop can look through objects, but doesn’t this type of loop look at the properties? Or does stating ////collection[val][pre]/// mean that with a for in loop that it looks at the values of the properties given? Thank you for your time, anyone!
Your code so far
function truthCheck(collection, pre) {
for (let val in collection) {
//i Set up a for in loop to iterate through the individual objects in the array
if(!collection[val][pre])
//if the value of collection[val][pre] which should match the value of the predicate is falsy or not true
{
return false;
//then return false
}
}
return true;
//else return true
}
console.log(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.
function truthCheck(collection, pre) {
for(let i=0 ; i< collection.length; i++){// iterate on the collection array
if(collection[i].hasOwnProperty(pre)=== false || !collection[i][pre]){/*check if the array record object doesn't have the pre property or have a value of not truthy*/
return false;
}
}
return true;
}
Thank you. That helped I think. The for of loop looks at everything and returns objects as the values, while the for in loop takes it a step further and looks at the values in the object because collection[val] = object, collection[val][pre] kinda takes it a step further and looks at the value of the predicate. Like the way arr[0][1] works for a nested array.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.
let arr = ["a", "b", "c"]
for (let i in arr) console.log(i) // this prints "0", "1", "2"
for (let v of arr) console.log(v) // this prints "a", "b", "c"
the for…in gives you the properties/indexes, the for…of gives you the values
if the values are objects, you can do whatever you can do with objects
I suggest you try again with the for…of loop, for practice and experience