For Loops : Javascript


#1

This is just a general question, I’ll provide an example:

So, I barely understand for loops. This is the only part of javascript that I am having difficulty with and I have an important assessment to take on Saturday so ur help will be much appreciated!

  1. function getColumn(puzzle, columnIndex){
  2. let column = [];
  3. for (let i = 0; i < puzzle.length; i++){
  4. column.push(puzzle[i][columnIndex]);

so on line 4, that is where I get stuck. I don’t know how to read that and this is what gets me on every problem that involves looping. I was hoping someone could explain to me how that block of code works and how it’s supposed to be read.

Thank you!


#2

We lack some context here so must go on some assumptions. First, that puzzle is iterable since it has a length; and second, that each row in puzzle is also iterable since it has an index.

The code in line 4 above is polling the value in row i at column columnIndex and appending it to the column array.

Addendum

Arrays have four methods to add or remove the first or last element.

array.push(object)
array.pop()

Using push(), the object is appended to the end of the array. The object can be any JS object, a number, character (or string), another array, an object, or a reference to an object elsewhere in the namespace.

Using pop() removes the last element. We can assign the value in the same process.

array.unshift(object)
array.shift()

The above methods do the same as the first two, respectively, only at the start of the list, not the end.

Iterating an array with two dimensions (as an array of arrays is given to have) requires two iterators, one for the rows, and one for the columns. (for is an iterator.)

for (row of array) {
    for (col of row) {

    }
}

Using the ES6 of operator we poll the values directly, without an index. We iterate over one row at a time, and then iterate over each value from left to right.

For this example I’m going to use a PlayFour puzzle by John Wilmes

JEER  ... TAUNT
ORCA  ... LARGE WHALE
LION  ... LARGE CAT
TENT  ... PUP(?POLE)
|||.  ... TIRADE
||._  ... SUPPLY AND DEMAND SUBJ.
|.__  ... GREAT LAKE
.___  ... SUDDEN SHOCK

Your for loop is able to recover the vertical words, using the column array.

const horz = ['JEER', 'ORCA', 'LION', 'TENT'];
const vert = [[], [], [], []];
for (col = 0; col < vert.length; col++) {
  for (row = 0; row < horz[col].length; row++) {
    vert[col].push(horz[row][col])
  }
  vert[col] = vert[col].join('');
}
vert.forEach(x => console.log(x));
JOLT
ERIE
ECON
RANT