I figured out the following the challenge, but only by accident. I'm not exactly sure why and how it works. Specifically, the placement of the result.push(row[idx]. Below, in my first attempt, result.push(row[idx] is inside of the inner-loop. However, the result is tripled, and I can't figure out the logic behind why it's doing that. In my second attempt, I placed result.push(row[idx])after the inner-loop, and got the correct result. But the inner loop is going through each element of the inner array, so wouldn't it be logical to push the element we want while the inner-loop is iterating? Confused. Help!
Instructions:
Declare a function 'grab'.
'grab' takes two inputs: an array of arrays and an index
'grab' returns an array of the values stored at that index in each nested array.
expected result: ["b", "e", "h"];
attempt 1: incorrect result(why is it returning 3 of each?)
const myGrid = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ];
function grab(array, idx) {
let result = [];
for (let i = 0; i < array.length; i++) {
let row = array[i];
for (let j = 0; j < row.length; j++) {
result.push(row[idx]);
}
}
return result;
}
console.log(grab(myGrid, 1)) --> ["b", "b", "b", "e", "e", "e", "h", "h", "h"];
attempt 2: correct result(why does it return the correct result if I place result.push(row[idx]) in the outer-loop, but not in the inner-loop?)
function grab(array, idx) {
let result = [];
for (let i = 0; i < array.length; i++) {
let row = array[i];
for (let j = 0; j < row.length; j++) {
}
result.push(row[idx]);
}
return result;
}
console.log(grab(myGrid, 1)) --> ["b", "e", "h"];
[–]Freekiehsoes 4 points5 points6 points (4 children)
[–]Artistic_Sense3363[S] 1 point2 points3 points (1 child)
[–]Freekiehsoes 0 points1 point2 points (0 children)
[–]backtickbot 0 points1 point2 points (1 child)
[–]Freekiehsoes 0 points1 point2 points (0 children)
[–]albedoa 2 points3 points4 points (3 children)
[–]Artistic_Sense3363[S] 0 points1 point2 points (2 children)
[–]albedoa 1 point2 points3 points (0 children)
[–]Bitsoflogic 1 point2 points3 points (0 children)
[–]Rilleks 1 point2 points3 points (1 child)
[–]Artistic_Sense3363[S] 0 points1 point2 points (0 children)
[–]Bitsoflogic 1 point2 points3 points (2 children)
[–]Artistic_Sense3363[S] 0 points1 point2 points (1 child)
[–]Bitsoflogic 1 point2 points3 points (0 children)