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

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

Obtaining the data from the React material-UI Autocomplete box

I have been exploring the React Material-UI documentation (https://material-ui.com/components/autocomplete/) and came across a query. Within the demo code snippet, I noticed the following: <Autocomplete options={top100Films} getOptionL ...

How to toggle between arrays using ng-repeat

Currently, I am managing 3 arrays and wish to toggle between them using ng-repeat: $scope.fooDataObj = { array1:[{name:'john', id:'1'},{name:'jerry', id:'2'}], array2[{name:'bill', id:'1'},{name: ...

Retrieving information from an Object within a JSON response

After calling my JSON, I receive a specific set of arrays of objects that contain valuable data. I am currently struggling to access this data and display it in a dropdown menu. When I log the response in the console, it appears as shown in this image: htt ...

What is the method for displaying the value of a textarea?

I am relatively new to the world of coding, but I have already delved into HTML, CSS, and basic DOM scripting. My goal is simple - I want to create a comment box where people can leave messages like in a guestbook. However, when I input text and click on ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

One of my AngularJS directives seems to be malfunctioning while the rest are working fine. Can you help me troubleshoot

Recently, I've been immersing myself in the job search process and decided to create a website as a sort of online resume while also learning AngularJS. I enrolled in the Angular course on CodeSchool and am slowly building my website to my liking. (Pl ...

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

What is the best way to show a nested div element within a v-for loop in Vue.js?

One interesting feature of my coding project is that I have an array nested within another array, and I iterate through them using two v-for loops. The challenge arises when I try to display a specific div in the second loop only upon clicking a button. ...

What techniques can I use to merge alpha channels with compositing in images?

Utilizing an HTML5 Canvas along with the KineticJS(KonvaJS) canvas library, I have successfully incorporated an Image element. My current objective is to erase specific pixels while maintaining a certain level of transparency. The red dot erases pixels at ...

Acquire the S3 URL link for the uploaded file upon completion of the file upload process

Is there a way to securely upload and generate a public Amazon S3 URL for a PDF file when a user clicks on a specific link? I'd like to avoid exposing the actual link to the user by uploading it to S3. Here's a sample code snippet: module.expo ...

Struggling to manage texbox with Reactjs

Currently working in Reactjs with Nextjs and encountering a problem with the "text box". When I use the "value" attribute in the textbox, I am unable to input anything, but when I use the "defaultValue" attribute, I receive a validation message saying "Ple ...

Insufficient module names remaining in NPM

Starting to release modules on NPM has been on my mind, but I can't help but worry about the limited availability of sensible module names in the public domain. Is there a way to create a public NPM module that organizes all my module names within a ...

Exploring the functionality of event.target.name.value

I've been struggling to make event.target.name.value work for an input field in my form. When I submit the form, the values appear as null and I have to click twice to get them. This is the code I've written: const [name, setName] = useState(& ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

Managing stream pauses and resumes in Node.js using setTimeout()

After some experimentation with Node.js (v4.4.7), I managed to create a simple program to play a sound... const Speaker = require('audio-speaker/stream'); const Generator = require('audio-generator/stream'); const speaker = new Speake ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...