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.
You should consider using the
for...ofloop on the values of the object instead. Example below.I also included an alternative in case you are allowed to get away from the for loop. In that alternative, you could map the object's values and filter the animals array of each person to return only the cats. Then, flatten the array, since the map result will be a nested array of arrays, and get it's length.