I have an exercise that requires me to use a for loop to iterate through the object 'tutorPetTypes' and calculate the collective total number of cats owned by the tutors.
Here's my current code. It runs but results in totalCats = 0, whereas It should be 7.
If I console.log(tutor) as part of the if statement, I can see that it's correctly iterating through the tutors but I'm obviously missing something in terms of correctly checking the array for "cat".
const tutorPetTypes = {
'Sarah': ['cat'],
'Jim': ['dog', 'dog'],
'Joe': ['mouse'],
'Róisín': ['cat','cat','cat','cat','cat','dog'],
'Edd': ['lizard', 'cat'],
'Lewis': ['bearded dragon', 'tortoise']
}
let totalCats = 0
//Solution to be provided below
for (const tutor in tutorPetTypes) {
for (let i = 0; i < tutor.length; i++) {
if (tutor[i] === "cat") {
totalCats++;
};
};
};
Any help would be greatly appreciated.
Thank you everyone for your responses.
I find it interesting how no one was willing to provide a solution using for... in, and I don't mean that in a critical way, just observational. As clearly there are more advanced functions that provide a more suitable solution to this exercise given that so many people suggested it i.e. Object.values. However, the exercise specifically required that I use the a for... in loop. (I don't know why) And your responses did help me in analysing my solution and eventually coming up with a working one. Which is this:
It simply needed
[tutor][i]
changing totutorPetTypes[tutor][i]
Previously it was iterating through each letter of the tutors name, hence
=== 'cat'
returned 0.