Modifying a single value within a 2D array has a ripple effect, altering the

While working on a basic game of life simulation, I encountered an unusual problem. I have a 2D array and I'm attempting to modify a single value at coordinates x,y. Sounds simple enough, right?

let arr = new Array(10).fill(new Array(10).fill(1))
arr[1][1] = 0
console.log(arr[3])

I've successfully done this in previous projects, but for some reason now it's affecting all values in arr[x][1] instead of just arr[1][1]

Answer №1

Using new Array creates an object (most things in JS are objects) that will be used to duplicate the same array 10 times. So, when you use arr[1][1] = 0;, you're actually modifying a property of the original object which is reflected throughout.

To demonstrate that it's the same object across the array, try comparing like arr[4] === arr[7] and you'll get a result of true.

Answer №2

When using the code new Array(10).fill(1), a reference is generated and used in each slot of the array. This means that modifying an index of any array will also update other arrays, as they share the same reference.

To avoid this issue, you can create a new reference for each index by utilizing array.from

You need to create a new reference of array for each index. You can use Array#from to generate it.

const arr = Array.from({length: 10}, _ => new Array(10).fill(1));
arr[1][1] = 0
console.log(arr)

Answer №3

JS Array Fill Method Explained illustrates how the fill method populates an array with a specified value.

To achieve this, follow the code snippet below:

const newArray = new Array(5).fill('Hello').map((elem) => new Array(5).fill(elem));

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 Three JS OrbitControls within a JQuery Draggable interface

My challenge involves using a canvas containing cubes inside a draggable element. I am trying to rotate the camera using OrbitControls, but I am facing an issue where instead of just rotating the cubes, it also starts dragging on left click (I would like t ...

The basic jQuery script seems to be malfunctioning

I am trying to attach an on click event to an li element using jQuery. I have written a simple jQuery code within the document ready function, but for some reason it is not functioning as expected. I have checked in both Chrome and Firefox, and there are n ...

Collaborating on interactive client and server content across JSP's

I've been researching the capabilities of JSPs extensively, but have yet to find a clear answer to my specific problem. Currently, I am developing a web application that utilizes a single JSP (with an imported CSS) to create a website with various fu ...

Javascript is utilized to populate text within a div, although the animation is exclusively applied to the initial text

I am currently working on designing a landing page that showcases a dynamic display of rotating texts with a typewriter-like animation effect. While I have successfully implemented the animation for the first text, I am facing an issue where the subsequent ...

Retrieve the object filtered by a specific group from an array of data

I have a data object that contains various groups and rules within each group item. My task is to filter the rules based on a search query, while also displaying the group name associated with the filtered rule. { "id": "rulesCompany", "group": [ ...

Displaying the array of structures

Why is my printList() function only outputting the last element added to the array by addInfo()? Is there a mistake in how elements are being added to the array? #include <stdio.h> #include <stdlib.h> //structure Location typedef struct Loc ...

What is the best way to design a button that can toggle a sidebar on and off

I'm struggling with creating a toggle button for the sidebar. I have the sidebar and the button ready, but I'm not sure how to make the toggle function work. Can someone please guide me on what steps I need to take to achieve this? Your help woul ...

"Using the push method in JavaScript allows for the combination of arrays rather than

Looking to retrieve data from an API and store it in an array. When I assign the value directly using '=', the desired data is displayed. However, when attempting to add elements using 'push', they are added as another array. Below is ...

Creating a multi-dimensional array in C++ with proper initialization

While reading a book, I came across an example that caught my attention. static int categoryTable[ 2 ][ 2 ][ 2 ] = { //!b!c !bc b!c bc 0, 3, 2, 2, //!a 1, 2, 1, 1 // a }; category = categoryTable[ a ][ b ][ c ] Upon fur ...

Retrieve information stored in a database

If I am looking to retrieve someone's name from a firebase database in order to display it in JSX for a React Native project, the rendering process could be as follows: return( <View> <Text>{name} retrieved data!</Text> </Vie ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Issue encountered during Expo managed app iOS build: "Encountered error: Unable to read property 'transformFile' of undefined."

I'm currently developing a managed expo app and utilizing eas services. When attempting to create an internal distribution build, the process is successful on Android, but on iOS, the build fails with the following error: Metro encountered an error: C ...

Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page? Below is a simple form code example: <form name="searchLocations" method="POST"> <select name="l ...

Sending Ajax requests to web services hosted on a dual-node NLB

I am currently managing a two-node NLB configuration where multiple web services need to be accessed from the client-side using ajax POST requests. When visiting the page at: http://clusternode1/ everything works smoothly. Similarly, when accessing it f ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

Utilizing Redux actions in React components

As I was delving into React and Redux concepts, I decided to create a simple component to gain a better understanding. Now, I am attempting to divide the Redux logic into a separate component, resulting in a total of two components. However, upon compili ...

I tried setting ajax async to false, but it doesn't seem to be functioning

I've been attempting to retrieve JSON data from another domain, and my code looks like this: var token = ''; function fetchData(){ console.log("Data fetched successfully"); for (var i=0; i < urls.length; i++){ var endpoint = &ap ...

Utilizing the loop counter within an Array

Currently, I am attempting to iterate through numbers 1 to 21 and then utilize those numbers in order to obtain an Array of Strings like ['e1.wkh',...'e21.wkh']. However, at the moment I am only receiving the value ['e21.wkh'] ...