Weird behavior observed in loop through 2D Array (FCC)

I'm currently engaged in a learning exercise and I am attempting to comprehend the code provided. While I believed I had a solid grasp of arrays and loops, this particular piece of code has left me feeling quite puzzled.

The code snippet below:

  function zeroArray(m, n) 
  {  
  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i++) 
  {    
    for (let j = 0; j < n; j++) 
    {      
      row.push(0);
    }    
    newArray.push(row);
  }
  return newArray;

 }

 let matrix = zeroArray(3, 2);
 console.log(matrix);

Returns

[ [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ] ]

However, my anticipated outcome was

[ [ 0, 0, ],
  [ 0, 0, 0, 0, ],
  [ 0, 0, 0, 0, 0, 0 ] ]

Based on the observation that during each iteration of i loop, we are appending (0) to row[] twice before inserting row[] into newArray.

Contrary to my expectation, upon inspection in my VSCode debugger, it appears that during each i loop, all existing indices of newArray are being updated with the most recent version of the row[] array.

What could be causing this phenomenon?

Answer №1

1) Begin the outer loop with i = 1 and iterate until i <= m, ensuring the loop runs m times

for (let i = 1; i <= m; i++) {

2) Every time the inner loop starts, generate a new row and add it to the newArray after the completion of the inner loop

3) Define the condition for the inner loop as j < n * i

  for (let j = 0; j < n * i; j++) {

function zeroMatrix(m, n) {
  let newArray = [];
  // const row = []   // (-)
  for (let i = 1; i <= m; i++) {
    const row = []; // (+)
    for (let j = 0; j < n * i; j++) { // (+)
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroMatrix(3, 2);
console.log(matrix);
/* This snippet is not directly related to the solution. It is just used to adjust the output height. Please ignore it */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To properly push to newArray, it is important to create a copy of the array:

function zeroArray(m, n) {
  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push(row.slice());
  }
  return newArray;

}

let matrix = zeroArray(3, 2);
console.log(JSON.stringify(matrix));

Answer №3

Matrix m x n represents m rows and n columns. Therefore, for dimensions 3, 2, the expected matrix is:

[
  [0, 0],
  [0, 0],
  [0, 0],
]

To achieve this, you can declare the variable row inside the first loop like so:

function zeroArray(m, n) {
  const newArray = [];

  for (let i = 0; i < m; i++) {
    const row = [];
    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;

}

let matrix = zeroArray(3, 2);
console.log(matrix);

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

How can you refresh the information shown in a separate component from the search input with a live search bar?

Currently, I am working on integrating a live search functionality into my Next.js application. While I have successfully managed to capture input changes, I am facing difficulties in filtering the results based on the user input. Here is a snippet of the ...

Issue encountered while utilizing PHP sessions

I'm currently developing a basic login page that utilizes JS, JQuery, and PHP. login.php <!DOCTYPE html> <head> <title>AJAX Login Learning Activity</title> <link rel="stylesheet" type="text/css" href="login.css"> ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

Is the concept of Controlled and Uncontrolled Components in VueJs similar to that of React?

When it comes to React, there is a distinction between controlled and uncontrolled components explained in detail at this link. Controlled components function within the React model where state is managed in the virtual DOM. In contrast, uncontrolled com ...

Organize the array of objects

Within my React state, I aim to rearrange a set of 3 objects by always placing the selected one in the middle while maintaining ascending order for the others. Currently, I utilize an order property within each object as a way to keep track of the sequenc ...

Retrieving data using ajax

I have set up an ajax script for a folder watcher. The folder watcher will return the variable $dir. Later on, the page containing the ajax script will retrieve the dir and then output it using PHP code. How can I access the variable so that I can simply ...

Upcoming examination on SEO using React testing library

Currently, I am in the process of testing out my SEO component which has the following structure: export const Seo: React.FC<Props> = ({ seo, title, excerpt, heroImage }) => { const description = seo?.description || excerpt const pageTitle = s ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Interact with multidimensional arrays using Vue JS

Is there a way to access properties within objects nested inside multidimensional arrays when using v-for with VueJS? var arr =[{"fruit": {"fruitName": "apple"}, "vegetable":[{"vegetableName": "carrot" }]}]; I am attempting to display it in the following ...

Fulfill the promise within the function upon clicking the button

I've created an intricate 'slideshow' using popups within a vue.js template. Each slide is a separate component, and the parent component cycles through them in a 'for' loop. Users navigate from one slide to the next by clicking a ...

How to sort objects by keys in AngularJS

Currently, I am working on building a sorting list using AngularJS. The goal is to have the data updated in the DOM dynamically when a user clicks on the name of a value. I am attempting to order the values by categories such as Bracelets, Charms, Earrings ...

What is the recommended port to use for utilizing Express on cPanel?

Trying to implement nodeJS on cPanel has been quite the challenge for me. I've noticed that I can only access pages that are served via 'vanilla' nodeJS. The default app.js file works perfectly fine and displays a message in the browser: va ...

"Utilizing Vue.js for frontend, this app utilizes axios from the client side, rather than

As a newcomer to the world of programming, I apologize if my question sounds basic. I currently have a setup where a Vue.js application is running on a Linux Red Hat server with Apache installed via XAMPP. Additionally, an ASP.NET Core 6 Web API applicatio ...

How to stop form submission when Enter key is pressed in Angular

Despite scouring stackoverflow for answers, none of the solutions have worked for me. I have tried various approaches, which I will outline below: <form (keydown.enter)="$event.preventDefault()" ...> <button (keyup.enter)="skillsHandleEnter($eve ...

Is there a way to clear the input value in the otp field?

Here is the codepen link I mentioned earlier: https://codepen.io/santoshch/pen/LYxOoWO <button @click="resetNow(id)"></button> resetNow(id){ this.$refs[`input-${id}`].input.value = ""; //In some cases, you may need to u ...

Can you provide the regular expression that will reject the character "?"

Can you help me verify that my form does not accept double quotes? Validators.pattern(/^(?!").*/g) The current solution is not functioning properly. I want to allow all characters except for double quotes. ...

The JavaScript code is executing before the SPFX Web Part has finished loading on the SharePoint page

I recently set up a Sharepoint Page with a custom masterpage, where I deployed my SPFx Webpart that requires certain javascript files. While the Webpart functions correctly at times, there are instances when it doesn't work due to the javascript bein ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...