Array help for using two for loops

var cars = [["A", "B", "C"],["D", "E", "F"],["G", "H", "I"]];
var diag = (cars.length*2) - 1
var result = [];

  for(i = cars.length - 1; i >= 0; i--) {
    for(j = cars.length - 1; j >= 0; j--) {
      const x = i;
      const y = diag - j;
      
        if( x>= 0 && y<= diag) {
            console.log(result)
        }
    }

Can someone help with this? Trying to start from bottom right to top left. I know I need a function too.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

So your j loop, which I assume you want to loop over the INNER arrays, should probably not be comparing to cars.length. Instead, at the first iteration (when i==0), you want to be setting j to cars[0].length-1. At the next iteration, when i==1, you want j to equal cars[1].length-1.

Each sub-array is found at a given index in the cars array. Can you think of a way, inside that inner loop, to get that? Hint: think about i.

Can you explain in detail what you are trying to do here? Can you show an example of the expected output in the console you want to achieve?

[["A", "B", "C"],
["D", "E", "F"],
["G", "H", "I"]];

[ I, F, H, C, E, G, B, D, A];

Trying to get it to read like that. From bottom right to top left.

That path seems strange to me. Why would you go from H to C?

Because it is going from bottom right to top left and that is the most bottom right after it cycles thru the array that forms a square.

For these kinds of problems, I try to figure out a pattern by mapping out the values based on their indices.

[
  [(0,0), (0,1), (0,2)],
  [(1,0), (1,1), (1,2)],
  [(2,0), (2,1), (2,2)]
];
[(2,2), (1,2), (2,1), (0,2), (1,1), (2,0), (0,1), (1,0), (0,0)]

See if this helps you to better understand the index relationships.