Why does the element from a nested array in javascript return as undefined when I try to access it?

Struggling to extract elements from a multidimensional array in JavaScript. Running into an issue where attempting to access elements from arrays within the main array using a variable results in undefined. Surprisingly, I achieve the desired outcome when utilizing a number instead of a variable.

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

for(let i=0; i < arr.length; i++) {
  console.log(arr[i][arr.length]);
}

Answer №1

To address the issue of the last array index being 2 when the array length is 3, you can make the following adjustment:

let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0;i<arr.length;i++){
  console.log(arr[i][arr.length - 1]); // Make sure to subtract 1
}

This code snippet will output 3, 6, 9

Answer №2

To access all elements within nested arrays, you'll need to utilize two for loops. One loop will iterate through the main array and another loop inside it will iterate through the inner arrays.

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

for(let i=0; i < arr.length; i++) {
  //looping through the outer array
  console.log(arr[i])
  for(let j=0;j< arr[i].length;j++)
  {
    //looping through the inner arrays
    console.log(arr[i][j]);
  }
  
}

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

Best method for adding markup content dynamically using XMLHttpRequest

How can we dynamically update content on a web page after successfully making an XML HTTP request? Let's use a specific example: User enters data in an input field (e.g. a forum post) Data is updated asynchronously using AJAX technology The forum po ...

Methods for reloading the requirejs module

There are two modules: settingmap.js var settingMap = { scWidth : [4000, 6000, 8000], scHeight : [5000, 7000, 9000], bxWidth : [100, 90, 80], bxHeight : [100, 90, 80], totalTime : [50, 40, 30], level : [1, 2, 3], boxColor : [&a ...

Efficiently converting HTML object data into plain text using RegExr in ReactJS and JavaScript

Is there a way to convert an object in JavaScript/ReactJS into a string? For instance, consider the following object: { article: '<p class="md-block-unstyled">First text...</p><p>Second text></p>' } I am looking to ...

Having issues with regEX functionality in an Angular form

I need to validate a phone number using regEX. My criteria is as follows: 10 digits alpha/numeric, where an Alpha CHAR is in the 4th position (excluding hyphens). For example: 586R410056  NNN ANN NNNN  (NNN) ANN NNNN  NNN-ANN-NNNN  (NNN) AN ...

What is the best way to retrieve form values on the server in nextJs?

I'm facing an issue with passing form data to my API endpoint in nextJS. I have set up the form using Formik and Yup for validation. Oddly, when I check the console on the client side, I can see the user input values just fine, but on the server side, ...

Enhancing JSON Objects in AngularJS with Custom Properties and Calculations

Hello, I'm still getting the hang of angularjs and could use some guidance. I have a Rest service that provides data on saleItems when a get request is made, as shown below: saleItems = [ { "id": 236, "variant": "Oval Holder", "mrp": "6 ...

What is the best method for effectively eliminating duplicate objects with the same value from an array?

Let's say we have a collection of jqlite objects, and using the angular.equals function, we can determine if they are equal. How can we utilize this function to eliminate duplicate items from an array of jQlite objects? This is my attempted solution: ...

"Terminate the current window that is open within the handler for the XMLHttpRequest

Currently, my approach involves using Javascript and Ajax to retrieve data and display it in a new window. I am encountering an issue where I am trying to close the window in the OpenFileWindow() function before opening a new one, but I am facing a permiss ...

Having trouble rendering only half of a sphere in three.js

I'm currently working on a skydome project in three.js and here is how I am approaching it: var geometry = new THREE.SphereGeometry( 40, 32, 15, 1*Math.PI/2, 2*Math.PI, Math.PI, Math.PI); var material = new THREE.MeshBasicMaterial( { color: 0xddddff ...

Manipulating DropDownList Attributes in ASP.NET using JavaScript

I am facing an issue with populating a Dropdownlist control on my ASCX page. <asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="bo ...

Steps for removing the label associated with an input field in an HTML form

I attempted to use JQuery and JavaScript in order to modify the CSS of a label to make it greyed out, but unfortunately I have not been able to achieve this. The label is positioned next to a checkbox, and although I am able to disable the checkbox, I hav ...

Incorrect comparison of floats within arrays resulted in inaccurate results

I am currently working on a project that involves comparing values in an Array which are dynamically fetched from a website, and I'm using Selenium-IDE to assist with this comparison. However, I've noticed that the values are being compared as s ...

Cease the use of jQuery animations

My JavaScript code snippet looks like this: $.get("/<page>.php", "userid='.$userid.'&"+status, function(data){ $("#status").show("fast").html(data).delay(4000).hide("fast"); }); On a page with multiple links triggering thi ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Issue with transmitting Razor form data to API controller using fetch or AJAX

I have created a basic razor web project and defined it as follows: in program.cs I added builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); In the controller, this is what I did: [Route("/api/[controller]")] [ApiCon ...

encountering problems with Next.js routing resulting in 404 errors

I developed a Next Js 14 app where I had to change the routing names inside the pages before going live. For example, instead of 'Charts', I changed it to 'charts' and made similar modifications to other pages as well. However, after de ...

Add a hyperlink within a button element

I am looking to add a route to my reusable 'button' component in order to navigate to another page. I attempted using the <Link> </Link> tags, but it affected my CSS and caused the 'button' to appear small. The link works if ...

Loading data onto a page using jQuery in ASP.NET after a postback

Currently experimenting with a jQuery plugin called jQuery Autocomplete Tokenizer. I'm facing an issue where I need to reload the values back into the textbox after the page is posted back, retaining whatever items were previously entered. Here' ...

Why isn't the show/hide feature in Jquery functioning properly?

I have a div that needs to be displayed after hovering over another element. These elements are not within the same div. The popup info should appear when an icon with the class .option_36_124 is hovered over. $(".option_36_124").hover(function(){ $(& ...

Using TextField with nested Object for onChange Event

I have a question that needs some clarification. Here is the current structure of my object. Within "allgemein," there are currently two variables, but they will increase over time... { id: "Abadi", name: "Abadi", type: "SC", allgemein: { ...