Omkar Verma
Omkar Verma

Reputation: 21

Access parent index in the child element in nested foreach in javascript

var game_board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

(function plot() {
  game_board.forEach((element, i) => {
    element.forEach((value, j) => {
      // access i here
      console.log(j);
    });
  });
})()

I have a multidimensional array and I want to access both indexes i and j.

Upvotes: 1

Views: 1314

Answers (2)

Mosia Thabo
Mosia Thabo

Reputation: 4267

Just for illustration:

var game_board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

function plot() {
  game_board.forEach((element, i) => {
    element.forEach((value, j) => {
      // access i here
      console.log(j, i);
    });
  });
}

plot();

Upvotes: 1

Nilanka Manoj
Nilanka Manoj

Reputation: 3728

Actually You have access:

var game_board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

game_board.forEach((element, i) => {
    element.forEach((value, j) => {
      console.log('i : '+i+', j : '+j);
    });
  });

Note: function arguments of parent function is accessible by child function wherever the nested positions are. So, foreach callback function behaves in the same way.

Upvotes: 1

Related Questions