How to retrieve the parent index from within a nested forEach loop in JavaScript

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

(function iterate() {
  game_board.forEach((row, i) => {
    row.forEach((value, j) => {
      // accessing indexes i and j
      console.log(i, j);
    });
  });
})()

I have a two-dimensional array and I need to access the indexes of each element in it.

Answer №1

Well, it turns out that you actually have access to:

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: Remember, function arguments of parent functions are accessible by child functions no matter how nested they are. This is why the foreach callback function behaves in a similar manner.

Answer №2

Just as an example:

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

function displayBoard() {
  board_game.forEach((row, rowIndex) => {
    row.forEach((value, colIndex) => {
      // access rowIndex here
      console.log(colIndex, rowIndex);
    });
  });
}

displayBoard();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this? Understanding how this works in JavaScript can be confusing. I have experiment ...

What is the reason tailwind does not take precedence over locally defined styles?

I've been experimenting with changing the default text color using Tailwind CSS, but for some reason, it's not taking effect. I've noticed that Bootstrap is able to override the default style without any issues. I'm fairly new to Tailw ...

Display the loading status while fetching data

I recently implemented a code snippet that allows users to download files to cache for offline viewing. You can check it out here: While the code works well, I've noticed that for larger files, the loading process can be a bit slow. I am looking for ...

Utilizing module.exports functionality within Express.js

Recently, I was working on a Discord bot using discord js and I wanted to integrate some frontend aspects to allow for changes through a website interface rather than just commands. However, I ran into an issue with utilizing module.exports in expressjs. I ...

Utilizing $http (REST) to send information from a form

Struggling to leverage Angular for CRUD processes, especially encountering difficulties with POST requests to the server. This is my controller: angular.module('myModule').controller("ListingCtrl", function($scope, posts) { $scope.addProje ...

Displaying Live Data to Users on Rails 3 using Node.js and MongoDB

I am experiencing an issue with my Rails web application where the data is not being displayed in real-time to users. Despite having a node.js server that is continuously updating a cloud database accessible by the Rails app, the data does not appear insta ...

Restrict the input to only allow for parentheses, disallowing any letters or numerical characters

Only parentheses are allowed in the input field; letters and numbers will not be accepted. function checkBrackets() { var inputVal = document.getElementById("input").value; var result = document.getElementById("strong").value; console.log(inputVal, ...

Signal check indicates that the Internet connection has been restored

One of the key requirements for my app is to load data into a database, which necessitates having an active Internet connection. I have been contemplating what to do in case of network failure - perhaps I can store the data locally on the device and synch ...

Implementing the array name property in a JSON object using ES5

I am currently working with a JSON object that has the following structure: {"Firstname":"john","Lastname":"doe"} My goal is to transform it into an array with a specific name 'abc': users: [{"Firstna ...

Having trouble changing the style property of the `<div>` element in my JS function within Bootstrap Studio

I am currently utilizing Bootstrap in Bootstrap Studio along with plain JavaScript. One of the challenges I am facing pertains to changing the background color of a <div> element upon selecting a new tab. The objective is to dynamically alter the ba ...

Showing a heading based on a value in Angular: A Complete Guide

I am attempting to dynamically change the title based on the item's _id value. I have stored the item in the component. Here is the HTML code I am using: <h1 mat-dialog-title>{{item._id ? "Update" : "Add"}} animal</h1> Below is my dialog ...

The Veux Store is throwing an error message that says "Array is

When retrieving data from the Vuex Store, I start by checking if the array is present. Following that, my next step is to verify whether the noProducts object at index 0 exists. This validation process is important because the tweakwiseSortedProducts vari ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

The Ajax request functions correctly in Chrome and Safari but encounters issues in Firefox and Internet Explorer

I've encountered an issue with jQuery where the call is failing when making a request with base64 authorization header in the beforeSend function. It's a simple request to retrieve projects. function GetProjects(full){ var query = "/Projects"; $ ...

Creating an empty array within an object in JavaScript

Consider the following scenario: var form = { header: { value: null, isValid: false, type: 'textinput', rules: { isRequired: true, ...

Is there a way for me to open this tr link in a separate tab rather than in the current one?

Is there a way to open this link in a new tab? <a href="....." target="_blank"> This is how it can be done using JavaScript: <script> $(document).ready(function(){ $('table tr').click(function(){ window.open($(this).att ...

What methods can I use to stop the styles of a child component from impacting those of the parent component

Is there a way to create CSS rules that achieve the following conditions? The parent component's CSS does not impact the child component The child component's CSS does not affect the parent component The child component is sourced from an exte ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...