Error when trying to assign values to an undefined property in an array

While working on a problem in Leetcode, I encountered an issue with an empty array. I attempted to push some numbers into it and received an error message that I am unsure of the reason for. Below is my code snippet:

// r and c values are pre-defined numbers, arr is also a pre-defined array.
let n = [[]]
let index = 0
for (let i = 0; i < r; i++) {
    for (let j = 0; j < c; j++) {
        n[i][j] = arr[index]
        index++;
    }
}
return n;

Leetcode flagged n[i][j] = arr[index] as erroneous.

If anyone can shed light on why this error occurred, I would greatly appreciate it. Thank you.

Answer №1

Once the variable i reaches a value of 1, it sets the value to n[i][j] within the inner loop, specifically n[1][0]. In this case, n[1] is not defined and attempting to access the 0th index of an undefined value results in an error.

The initial iteration functions correctly as there is already an empty array at the 0th index (i = 0).

To address this issue, consider utilizing the following code snippet:

let n = [];
let index = 0;
for (let i = 0; i < r; i++) {
    n[i] = [];
    for (let j = 0; j < c; j++) {
        n[i][j] = arr[index];
        index++;
    }
}

return n;

Answer №2

After receiving feedback from other users, I learned that the .push method can be used in this scenario. Here is how I incorporated that approach into my own project:

let newArray = [[]];
const rows = 6;
const columns = 9;

for (let i = 0; i < rows; i++) {
    if (i > 0) {
        newArray.push([]);
    }
    
    for (let j = 0; j < columns; j++) {
        newArray[i][j] = "y";
    }
}

console.log(newArray);

Check out my implementation on CodePen

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

Flashing white screen when transitioning between pages on phonegap iOS system

I'm currently using phonegap for my iOS application project. Interestingly, I've noticed a slight white flicker/flash when navigating between pages in the app. To address this issue, I have refrained from using jquery mobile and instead relied ...

Synchronization problem encountered in an Angular app involving playwright

Currently, I am working on automating a process where the service queries the database and displays the data on the user interface. However, the rendering takes a considerable amount of time, around 3 minutes. Despite using Playwright for automation, it do ...

Reveal the concealed element

My webpage features a hidden span element within a div that I would like to reveal when a button is clicked. However, the functionality is not working as expected. Here is my code: <!DOCTYPE html> <html> <head> <meta charset="ut ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

What is the best way to place content in a single div without it being divided into several separate boxes

Here is my code snippet: <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"&g ...

What are the steps to implementing AOP in node.js?

I am facing a challenge with implementing AOP in node.js: Imagine I have an application in a script named server.js, and I need to track its functions. Here is the code snippet: var express = require('express'); var app = express(); app.get(& ...

What is the reason behind every single request being treated as an ajax request?

Recently, I embarked on a new application development journey using rails 4.0. However, I've encountered an unexpected situation where every request is being processed as an ajax request. For instance, consider this link: =link_to "View detail", pr ...

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

Utilizing a dynamic ref in Vue using the composition API

While working with the composition API in Vue 3, I am trying to create a reference to a component dynamically. Typically, this would involve adding ref="name" to the template and then defining a ref using const name = ref(null). However, I am loo ...

The Access-Control-Allow-Origin header seems to be ineffective while implementing an axios post request in a React application

While attempting to send an object to the API, I encountered the following issue: Access to XMLHttpRequest at 'https://ciboservis.herokuapp.com/api/v1/filial/adm' from origin 'http://localhost:3001' has been blocked by CORS policy: Resp ...

Loop through the list items using jQuery and retrieve the value of the data-imgid attribute

Multiple li elements have a unique data-id attribute, as shown below: <ul> <li data-imgid="5" class="getMe">some text</li> <li data-imgid="6" class="getMe">some text</li> <li data-imgid="7" class="getMe">some t ...

Troubleshooting issues with the Select List component in ReactJS

Having an issue with the select list as the onChange event is not triggering. Struggling to set the selected value from the list in the this.state variable. Any assistance on this matter would be greatly appreciated. class SelectActivity extends React.C ...

Creating nested tabs using vanilla JavaScript, no need for jQuery

I am currently working on implementing tabs using a JavaScript function. The issue I am facing is that when I try to have tabs within one of the tabs, everything disappears every time I click on one of the inner tabs. This happens because the JavaScript fu ...

Error encountered: Function _ctx.showEditModal is not defined in Vue 3 + Laravel Project

Currently, I am working on a Laravel + Vue Js 3 project. Within my Tags.vue file, there is an edit button that should lead to the tag edit page. You can view the Tags.vue file through the following link: https://codepen.io/amumodaya/pen/abjqXbV However, ...

Efficient solution to transform a boolean array to a string: 'false, true, true, false'

Is there a concise way to convert an array of booleans into a string like "false, true, true, false" using minimal lines of code? In Python, it can be done elegantly with the following snippet: ", ".join(map(str, [False, True, True, False])) Unfortunate ...

Utilizing a navigation menu to display various Strapi Collection pages within a single Angular Component

I have set up a collection in Strapi called Pages and I am looking to display them in the same component using my Navigation Bar Component. However, I am unsure of how to achieve this. Currently, all the data from the Collection is being displayed like th ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Enhance your map by incorporating an overlay with ngx-openlayers

Currently, I am trying to implement zoom-in and zoom-out buttons on an OpenLayers map. I attempted to use the overlay method but encountered an error. Here is the code snippet for reference: zoom_button = document.getElementById('zoom') zo ...

Avoid activating automatic save feature in Material UI data grid

After creating a data-grid and attempting to add records, I encountered an issue where pressing the TAB key automatically saved the data when focusing on the save button without manually pressing enter. How can this behavior be prevented so that manual con ...

Sustaining the Status of a Changeable Form Element

To fulfill the requirement of constructing a Form Builder component that generates forms based on JSON data from the backend, I have identified 7 types of input fields that may be encountered: email password select file date input of type text input of ty ...