The function Slice() does not function properly when used with two-dimensional arrays

I have been attempting to duplicate a 2D array by value using the slice() method in order to prevent any changes made to the new array from impacting the original. Oddly enough, it seems that this approach is effective with a 1-dimensional array but not with a 2-dimensional one.

Below is the code I've been working on:

var arrayA = new Array(5); // Create a 2D array
for (var i = 0; i < 5; i++) {
  arrayA[i] = new Array(5);
}
for (var x = 0; x < 5; x++) { // Populate the original array
  for (var i = 0; i < 5; i++) {
    arrayA[x][i] = x + i;
  }
}
arrayB = arrayA.slice(); // Create a new array (1)
arrayB[0][0] = 10;
var arrayC = arrayA.slice(); // Create another new array (2) to observe changes when using var
arrayC[0][0] = 100; // Modify the first element of the last array


$(document).click(function() {
  alert(arrayA[0][0]); // Outputs 100
  alert(arrayB[0][0]); // Outputs 100
  alert(arrayC[0][0]); // Outputs 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If anyone knows why the slice method doesn't work properly with multi-dimensional arrays and if there is a workaround for this issue, your insights would be greatly appreciated. Thank you!

Answer №1

The reason arrayA[0] acts as a reference to array, not the actual array itself. Therefore,

arrayB[0][0] = 10; and arrayC[0][0] = 100; modify the same array. To make independent changes, you must clone the inner array:

var x = [[0,1,2,3],[0,1,2,3]];
var y = x.slice();
var z = x.slice();
y[0] = y[0].slice();
z[0] = z[0].slice();
y[0][0] = 10;
z[0][0] = 100;

console.log(x[0][0], y[0][0], z[0][0]);

If deep cloning is needed, it's recommended to use JSON.parse(JSON.stringify(a));

Answer №2

.slice function did not create a deep copy but only copied the references to the original array elements. To achieve a deep copy, you can utilize JSON.parse and JSON.stringify methods as shown below:

var arrayA = new Array(5); // Creating a 2D array
for (var i = 0; i < 5; i++) {
  arrayA[i] = new Array(5);
}
for (var x = 0; x < 5; x++) { // Populating the original array
  for (var i = 0; i < 5; i++) {
    arrayA[x][i] = x + i;
  }
}
arrayB = JSON.parse(JSON.stringify(arrayA));
arrayB[0][0] = 10;
var arrayC = JSON.parse(JSON.stringify(arrayA));
arrayC[0][0] = 100; // Modifying the value of the first element in the last array

$(document).click(function() {
  alert(arrayA[0][0]); // Outputs 0
  alert(arrayB[0][0]); // Outputs 10
  alert(arrayC[0][0]); // Outputs 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

Increase in textbox size depending on selected dropdown value

Our concept involves offering three choices: Email #1 pulled from the database Email #2 retrieved from the database Input a new email Should the user select option #3, a textbox will expand at the bottom of the dropdown menu for easy entry of a new emai ...

Finding the precise top offset position with jQuery upon scrolling – a step-by-step guide

I need help with detecting the offset top of a TR element when it is clicked. It works fine initially, but once the page is scrolled, the offset().top value changes. How can I resolve this issue? $(function() { $('tr').click(function() { ...

What is the best method to prevent next.js components from overlapping one another?

I recently created a website using next.js and noticed an issue in my index.js file. There is a div that houses the main components of the site: class Page extends Component { render() { return ( <div className={styles.container}> ...

What is the best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...

Showing an array in angular.js

When sending data to a PHP file, the file processes it and performs an SQL search, returning a list of names in a for each statement. For example: Ryan, Jack, Billy, Sarah. However, when echoing the response in Angular, all the names are joined together l ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Enhancing JSON Objects in AngularJS with Custom Properties and Calculations

Hello, I'm still getting the hang of angularjs and could use some guidance. I have a Rest service that provides data on saleItems when a get request is made, as shown below: saleItems = [ { "id": 236, "variant": "Oval Holder", "mrp": "6 ...

Encountered a snag while executing Powershell with Selenium: Error message - unable to interact with

Looking to update a textarea with a value? The script below triggers an error stating "element not interactable". This occurs because the textarea is set to "display:none". However, manually removing the "NONE" word allows the script to successfully set th ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

EffectComposer - Retrieve the visual output produced by the Composer

Hey there, I've encountered an issue with the EffectComposer that I could use some help with. Here's what I'm attempting to do: I'm working on dividing up the post-processing effects in my App across different EffectComposers. My goal ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Guide to creating completely static HTML using `nuxt generate`?

Looking for a solution to ensure that Vue pages are fully generated as static HTML files in Nuxt even when they are simple and don't require any dynamic data fetching? Let's dig into the issue. <template> <div>hello world</div&g ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

The application of Uglify to eliminate console logs can be inconsistent in its effectiveness

Having some trouble with my Vue3 app. I've implemented UglifyJS to remove console.logs in production environments, but it seems to be inconsistent. Sometimes it works fine, other times not so much. Every time I have to rebuild and hope for the best. I ...

What is the best way to imitate a DOM in order to effectively test a Vue application with Jest that incorporates Xterm.js?

I've created a Vue component that displays an Xterm.js terminal. Terminal.vue <template> <div id="terminal"></div> </template> <script> import Vue from 'vue'; import { Terminal } from 'xterm/lib/public ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...