ArrayBuilder Challenge

I ended up looking up the answer for this after trying on my own. I understand whats going on all the way up until the while loop. I followed along on python tutor as well, but I cant wrap my head around on how the while loop after its first loop, that it doesn’t go straight to dog after pushing cat into the array the first time.

I would expect the loop to count down from 2 (count down because of the counter -= 1) but instead of starting back at the top of the object to push ‘cat’ in again, it would continue to work down the object with the next value which is ‘dog’ and then push that in…and THEN it would go back up to the top of the object again and push ‘cat’ into the array and then stop because then the counter would be finished.

so in other words why would the output be [‘cat’, ‘cat’, ‘dog’] and NOT [‘cat’, ‘dog’, ‘cat’]??

function arrayBuilder(obj) {
  const array = []
	for (let key in obj) {
    let counter = obj[key] 
		while (counter > 0) {
      counter -= 1
  return array

// Uncomment these to check your work!
console.log(arrayBuilder({'cats': 2, 'dogs': 1})); // => ['cats', 'cats', 'dogs']

Hello deboer753!
Looking at the code, see how the entire while loop is inside the for loop?
Since the while loop is inside the for loop, each time the while loop is executed, it will finish before the next for loop iteration.
So, when we enter the for loop the first time, counter becomes 2, and the while loop is then entered. counter is 2 so it executes once, pushing ‘cat’, and then counter is 1. Since counter is still > 0, the while loop executes again, pushing another ‘cat’. Then counter is 0, so the while loop stops and we go through the for loop for the second time, pushing ‘dog’.
Hopefully this helps!

I had to read that like 20 times, but it’s starting to make sense now. Thank you

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.