Yeah, your problem here is that return
kicks you out of whatever loop or function you are in to return the value and STOP.
So, save return for the one time you want to return your actual answer. (You will often see return used many times, but it is usually because a function contains other functions, or higher-order functions like map
, reduce
or filter
).
If you want an array of arrays, you can loop through them as you normally would, but you might want to nest a loop within a loop.
Here is a rough example (beware, they use up more computer resources AND more mental resources!):
var array = [[1,2,3], [4,5,6], [7,8,9]] // Array of arrays
for (var i = 0; i < array.length; i++) { // Outer loop
for (var j = 0; j < array[i].length; j++) { // Inner loop
console.log(array[i][j]); // what do you expect
} // this to log?
}
This can take a bit of concentration to get the hang of, so read it a few times to figure out what it is doing.
Notice that the outer loop uses i
as the counter / array index. This tracks the three items in the first level of the array.
The inner loop uses j
as the counter / array index. This tracks the three items in each of the second level arrays! Also, notice that the inner loop compares j
to the length of array[i]
, not just array like the previous one did…
Now, you may find that there is a better solution than using nested loops altogether…but hopefully this is enough of a pointer to help you understand your current approach.
To solve your return
problem, try assigning values to variables or constructing new arrays. Only return the solution.
ps: here’s a pen that will show you what the nested loops I wrote do (but try and figure it out first!): http://codepen.io/Malgalin/pen/JRVZjE?editors=0012
Edit
Oh, and in future, please start a new thread if you have a question about a different challenge. You are likely to get more eyes on it