Adjusting elements within nested JavaScript arrays

When using the code below, an empty array containing 7 empty arrays is expected to be created, essentially forming a 7x7 grid.

While accessing elements within nested arrays seems to work correctly, attempting to modify their values causes all elements in the same column to change (i.e., adjusting [1][1] also affects [0][1], [2][1], and so on). The reason for this behavior remains unclear to me.

var usage = new Array(7).fill(new Array(7).fill(0));

usage[1][1] += 1;

Check out this JSFiddle link for more information.

Answer №1

It's a common pitfall that many developers can stumble into. The code you provided can be simplified to:

var innerArray = [0,0,0,0,0,0,0]; 
var usage = [innerArray, innerArray, innerArray, innerArray,
             innerArray, innerArray, innerArray]; 

console.log(usage[0]==innerArray); // true
console.log(usage[1]==innerArray); // true

To achieve the desired outcome, you must create a new array for each element within 'usage'. You can do so by following this example:

var usage = [];
for (var i=0; i<7; i++) {
    usage.push(new Array(7).fill(0));
}

Answer №2

When the first instance of fill is executed, it creates an array which is then duplicated 7 times, resulting in all arrays being interconnected.

To illustrate this concept:

var t1 = new Array(7).fill(0);

var t2 = t1;
var t3 = t1;
var t4 = t1;
var t5 = t1;
var t6 = t1;
var t7 = t1;

t2[3] = "duplicate"

console.log(t1);
console.log(t2);
console.log(t3);

This will display identical values for t1 through t7.

Answer №3

It appears that the issue at hand may be stemming from your utilization of the .fill() method. By referring to the documentation here, it becomes evident that this method populates an array with a constant value.

In essence, when you access usage[1][1], you are essentially accessing the same array element found in usage[0][1], usage[2][1], and so forth.

To overcome this limitation, one can employ a for loop to populate the array as depicted below:

var usage2 = new Array();

for(var i=0; i<7; i++) { 
    usage2.push(new Array(7).fill(0));
}

By adopting this approach, you will observe the intended outcome where modifications affect only a single array, akin to the illustration captured from my Chrome console screenshot below.

https://i.sstatic.net/4NkP6.png

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

What is the reason for my Firestore listener consistently retrieving data from the server despite having offline persistence enabled?

Incorporating Firebase JavaScript Modular Web Version 9 SDK into my Vue 3 / TypeScript application. My understanding is that when utilizing real-time listeners with offline persistence in Firestore, the process should proceed as follows: Upon initializat ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

The 'RegExpExecArray | null' type is required to include a method '[Symbol.iterator]()' which returns an iterator to iterate through its values

As someone who is new to TypeScript, I have a good understanding of the basics but recently came across a typecast error that I am struggling to solve. const [full, id]: string | null = /.*media\/[^\/]+\/(.*)/.exec(item.uri) When it comes t ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

Tips on transferring dynamically generated results to a user-friendly print window

After users complete a quiz, they receive their results. The client now wants to implement a "Print Results" feature that opens in a new window with customized CSS. I'm trying to figure out how to transfer the results to the new window using JavaScri ...

Output JSON data using Javascript

Here is some JSON data I am working with: { "lang": [ { "SECTION_NAME": { "english": "My title" }, "SECTION_NAME_2": { "english": "My title" } } ] } I ...

Combining Multiple Optional Async AJAX Calls

In my Angular 1.5.8 app, I have different views that require various combinations of the same 3 ajax requests. Some views need data from all three endpoints, while others only need data from one or two. To efficiently manage the retrieval of this data, I ...

The process of using Jest to test whether a React component correctly renders a list

I've been diving into the world of unit testing and recently developed a small React application that showcases a list of Pokemon. My goal is to create a unit test that verifies if the list renders correctly. However, when I generate a snapshot, it on ...

Is it possible to retrieve information from Wikipedia using Ajax?

Does anybody know of a service or api that makes it possible to fetch Wikipedia data related to a specific topic using only JavaScript? ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Leverage Axios in React to dynamically fetch and display real-time data

Executing an Axios get request in order to retrieve data and display it using React. export function Wareh() { const [wareh, setWareh] = useState([{}]); useEffect(() => { axios.get("http://localhost:1515/wareh").then((response) => ...

Arrange the complex nested array or final JSON based on the key's name

I am currently in the process of sorting a rather large multidimensional array based on key names (and not values), while also aiming for the fastest possible solution. The resulting array will be converted to JSON and stored in a file, so if there is a m ...

We are experiencing difficulties rendering flash messages in Expressjs with Handlebars(hbs) and express-messages using flash-connect

I'm working on an express app and I want to display flash messages when a user signs up using a form. The technologies I am utilizing include Node.js, Express.js, Handlebars(hbs), connect-flash, and express-messages. To make finding errors easier, I ...

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

Delete JSON row columns efficiently without the need for iteration

Looking for a way to filter out specific data from your JSON object without looping through the entire thing? Here is a sample of the JSON data: [ { "cost":"KES 0.8000", "messageId":"ATXid_0fae395279b54d51519de5581230a7e ...

Is Eval really as bad as they say... What alternative should I consider using instead?

After making an ajax request, a JSON array filled with user inputs is returned to me. The inputs have already been sanitized, and by utilizing the eval() function, I can easily generate my JavaScript object and update the page... However, there lies a dil ...

How can I retrieve an updated object array within an extended class in JavaScript?

Hey everyone, I am new to working with ES6 classes. Currently, I am trying to inherit an initialized object (this._obj) with updated data in the class B, but I am encountering an issue where I am getting the length of the initialized object instead of the ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...