Troubleshooting a Multi-dimensional Array Reference Issue

Currently, I am working with an Array and need to modify the last item by pushing it back. Below is a simplified version of the code:

var array = [
                 [ [0,1,2], [3,4,5] ]
            ];

//other stuff...

var add = array[0].slice(); //creating a clone of the array (not functioning as expected)
add[0][0] = 10;
array.push(add);

console.log(array);

Here is the resulting output:

       

Upon inspection, both the first and second items in the array have their first element changed to 10. How do I go about resolving this issue? The array has already been cloned.

Answer №1

Array.prototype.slice() creates a shallow copy, meaning nested arrays are not duplicated. To achieve a deep cloning effect, it is recommended to use a method like the one described here.

Answer №2

When using Array.prototype.slice(), be aware that it does not actually clone nested arrays. To address this issue, you can employ a technique like the one demonstrated below:

var array = [
                 [ [0,1,2], [3,4,5] ]
            ];

//additional code...

var copy = array[0].slice(); //create a shallow copy of the array (note: this may not fully clone nested arrays)
copy[0] = array[0][0].slice();
copy[0][0] = 10;
array.push(copy);

console.log(array);

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

Transmitting data from the backend to AngularJS during page load

After diving into Angular JS for the first time, I've hit a roadblock at an essential stage. My setup consists of an AngularJS front end and Grails backend. Check out the code snippets below along with my query. URL Mapping entry: as "/graph"(cont ...

Navigating through the URL using an AJAX request with jQuery

After seeking assistance on how to loop through data in a json file from an asynchronous AJAX call in jquery using callback functions (Looping through AJAX and callbacks in jquery), I received valuable help. Now, I am curious about the possibility of loo ...

Update the array in state by adding a new element using setState

How can I add a new element to an array using setState? Consider the following data: this.state = { items : [ { "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }, { "id" : "24", "parent" : "dwdw", "text" : "Root node" }, { "id" ...

Identify modifications to properties in Angular

What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component: ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...

Tips for retrieving keycodes/key/which values for DOMSubtreeModified Event

Searching for the keycode pertaining to the DOMSubtreeModified event, but encountering undefined results <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> $(document).ready(function(){ ...

A singular Vuejs Pinia store utilizing namespaced actions

Is it possible to separate pinia actions into two distinct namespaces, allowing access through properties n1 and n2 like this: // current store.n1a('hi') store.n2b() // wanted store.n1.a('hi') store.n2.b() // cumbersome workaround: sto ...

Sort slider items using Show/Hide feature in bxSlider

I am using a bxslider on my website with specific settings: $('#carousel').bxSlider({ slideWidth: 146, minSlides: 2, maxSlides: 6, speed:500, adaptiveHeight: true, moveSlides:3, infiniteLoop : false, hideContr ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

Methods for extracting the date value from a Material UI datepicker?

As a newcomer to React, I am currently working on creating a form that includes a Date picker for scheduling appointments. Since booking appointments in the past is not allowed, I need to disable the days before today in the calendar for the date picker. ...

Integrate PHP include files into a website without allowing direct access, then dynamically load them using jQuery AJAX

I am utilizing jQuery AJAX to load the content of about.php page into my index.php section in this manner: $('.nav a[href="#about"]').on('click', function() { $('main').load('../../layout/about.php'); }); The iss ...

Leveraging the 'window' object as a dependency in the useEffect hook within NextJS

I'm encountering an issue where I need a function to run when the type of window.performance.getEntriesByType("navigation")[0].type changes. I attempted to use useEffect for this purpose, but it resulted in a 'window is not defined&apos ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...

Tips for guaranteeing that the value is retained in an array when setting a Cookie in AEM/cq5

I'm facing an issue with AEM where the page path needs to be added to a cookie each time a user visits a specific type of page. The requirement is to store a maximum of 3 pages in the recently visited section of the cookie. Initially, I attempted to u ...

I'm currently facing difficulties trying to implement AJAX with JavaScript and PHP as the desired output is not being

My query is quite straightforward - why isn't the code functioning properly? I am attempting to have the text echoed in PHP displayed inside a div with the ID of "show". Interestingly, this works with a txt file but not with PHP or any other type of f ...

Tips for adding color to the <td> element in an ejs file using nodeJS

I am looking to incorporate a color into my .ejs file. Here is the code snippet I am working with: <% resultList.forEach(function(item, index){ %> <tr> <td><%= item.function %></td> <td><%= item.value %>< ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...