Whale Talk - returning multipe arrays - why?

I’ve been working the Whale Talk project and all is fine, and working well to this point:

const input = 'You are already a coder!';
const vowels = ['a', 'e', 'i', 'o', 'u'];
const resultArray = [];

for (let i = 0; i < input.length; i++) {
  //console.log(i)
  for (let v = 0; v < vowels.length; v++) {
   //console.log(v)
   if (input[i] === vowels[v]) {
    console.log(input[i])
   }
  }
}

When I change the final console log line to push the result to the array (as per below), I get multiple arrays returned, and I’ve no idea why. I’ve compared my code to the video guide, and as far as I can see, I’ve done the exact same but the result is different on the video. Help appreciated!

const input = 'You are already a coder!';
const vowels = ['a', 'e', 'i', 'o', 'u'];
const resultArray = [];

for (let i = 0; i < input.length; i++) {
  //console.log(i)
  for (let v = 0; v < vowels.length; v++) {
   //console.log(v)
   if (input[i] === vowels[v]) {
    resultArray.push(input[i]);
    console.log(resultArray)
   }
  }
}

Result displays as:

Output-only Terminal
Output:
[ 'o' ]
[ 'o', 'u' ]
[ 'o', 'u', 'a' ]
[ 'o', 'u', 'a', 'e' ]
[ 'o', 'u', 'a', 'e', 'a' ]
[ 'o', 'u', 'a', 'e', 'a', 'e' ]
[
  'o', 'u', 'a',
  'e', 'a', 'e',
  'a'
]
[
  'o', 'u', 'a',
  'e', 'a', 'e',
  'a', 'a'
]
[
  'o', 'u', 'a',
  'e', 'a', 'e',
  'a', 'a', 'o'
]
[
  'o', 'u', 'a', 'e',
  'a', 'e', 'a', 'a',
  'o', 'e'
]

Your array is correct. It only looks like it’s returning multiple arrays because your console.log(resultArray) is in your for loop and it’s being reprinted every time you update the array. That can help when testing your code, but if you only wanted to print the array once, it needs to be outside both for loops.

2 Likes

@beta4571970086 Thank-you! That’s so obvious, but I was oblivious!