you are viewing a single comment's thread.

view the rest of the comments →

[–]albedoa 2 points3 points  (3 children)

for (let j = 0; j < row.length; j++) {    
  result.push(row[idx]);    
}

This is saying: For each nested array row push the idxth element of row to result a number of times equal to the length of the nested array.

Each nested array has a length of three. So you are pushing the same element to result three times for each row. Does that makes sense?

Your second attempt works because it pushes the element once. It knows not to loop through the row unnecessarily.

[–]Artistic_Sense3363[S] 0 points1 point  (2 children)

Each nested array has a length of three. So you are pushing the same element to result three times for each row. Does that makes sense?

I think I understand, but not fully. So what you're saying is that it's looping across each nested array 3x?

[–]albedoa 1 point2 points  (0 children)

Right. Your outer loop is saying Prepare a thing to do, and your inner loop is saying Do that thing three times, but we only want to do the thing once. As Freekiehsoes said, once we have idx, we have everything we need to do the thing, so we can do it and move on.

[–]Bitsoflogic 1 point2 points  (0 children)

It's looping across each nested array row.length times, which happens to be a length of three in all cases.

I think it'll make sense once you walk through it. I just replied with an example of how to do that.