0

how do loop through this 3x3 grid of arrays horizontally and print out 1, 4, 7, 2, 5, 8, 3, 6, 9?

edit: is there a more efficient way of doing this other than to use a two loops that also works if the length of the arrays are not equal to the other ones?

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

3
  • Will the individual arrays allways be the same length? Commented Oct 6, 2018 at 14:59
  • yes, but I'd like it to be smart enough to dynamically check that Commented Oct 6, 2018 at 15:00
  • Please have a look at my edit if you just want to make use of a single loop. @totalnoob Commented Oct 6, 2018 at 15:28

8 Answers 8

3

You can use nested for Loops:

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
for(let i = 0; i < grid[0].length; i++){
  for(let j = 0; j < grid.length; j++)
    console.log(grid[j][i]);
}

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. is there a better way instead of using two loops?
@totalnoob There must be a better way, but you will have to use nested loops :-)
I've posted answer with single loop, you can use division and reminder of division to get indexes. @totalnoob
3

You have a lot of answers that work if the arrays are all the same length. Here's a way to handle potentially different length arrays. It basically runs until it can't find any more data:

let grid = [
    [1, 2, 3, 4, 5],
    [4, 5, 6, 7],
    [7, 8, 9, 10, 11, 12]
  ];

let current = grid, i = 0
while(current.length){
    current = grid.filter(arr => i < arr.length)
    current.forEach(arr =>  console.log(arr[i]))
    i++
}

3 Comments

this is good! thanks. how's the complexity of this compare to the double loop solutions?
The complexity should be (number of rows) * (length of longest array). That's going to be similar to the others. In terms of total number of elements, however, this looks at each array even if there are no more elements (the shorter arrays are inspected even when the index is undefined).
On second though @totalnoob, you can probably improve this by only looking at elements that have data left in them. See edit.
1
for(var i = 0; i < grid.length; i++) {
    var arr = grid[i];
    for(var j = 0; j < arr.length; j++) {
        console.log("array[" + i + "][" + j + "] = " + arr[j]);
    }
}

Comments

1

you just have to find the sizes of the inner array and outer array

for(let i=0;i<countYourArraySize;i++)
{
for(let j=0;j<countYourInnerArayLength;j++)
{
console.log(grid[j][i])
}
}

Comments

1

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

let gridLength = grid[0].length;
let gridHeight = grid.length;
for(let l1=0; l1<gridLength;l1++) {
    for(let l2=0; l2<gridHeight;l2++) {
        console.log(grid[l2][l1]);
    }
}

Assuming grid is rectangular(and grids usually are ;)), you can loop through it, columns first, rows second like in this snippet.

There was a question if we can do it without 2 loops, we can and I think its actually better and cleaner solution:

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

let gridLength = 3;
for(let l1=0; l1<gridLength*gridLength;l1++) {
    console.log(grid[l1%gridLength][Math.floor(l1/gridLength)]);
}

Comments

1

You can do it with just one (explicit) loop if you use map:

let grid = [
 [1,2,3],
 [4,5,6],
 [7,8,9]
];
let result = [];
for (let i=0; i < grid.length; i++) {
    result = result.concat(grid.map((row) => row[i])));
}
console.log(result);

1 Comment

that's a pretty cool solution. how does the complexity of this compare to using two for loops? map itself is a loop right?
1

You can do this in a single loop. But the length must same for this

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

for (var i = 0; i < grid.length*grid.length; i++) {
    var row = Math.floor(i / grid.length);
    var col = i % grid.length;
    console.log(grid[col][row]);
}

Comments

1

You need to make use of a nested for loop:

So please have a look at my solution:

let grid = [
     [1,2,3],
     [4,5,6],
     [7,8,9]
];
for (let x = 0; x < grid[0].length; x++) {
    for (let y = 0; y < grid.length; y++) { 
      console.log(grid[y][x]);
    }
}


This grid prints out the expected solution: 1, 4, 7, 2, 5, 8, 3, 6, 9?


Some explanation:

In this case we are using two different for-loops.

  • the outer one for the X for (let x = 0; x < 3; x++) {}
  • the inner one for the Y for (let y = 0; y < 3; x++) {}

Note: This will just work if the grid is rectangular because using grid[0].length will otherwise produce an error.


Edit: If you just want to use a single loop try something like this:

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

for (let i = 0 ; i < grid.length * grid[0].length ; i++)
     console.log(grid[i % grid.length][parseInt(i / grid.length)]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.