Modifying the copied array will influence changes in the original array as well

Encountering a Puzzling Dilemma:

I recently created a copy of an array and was surprised to find that when I made changes to the copied array, the original array also changed. Why did this happen?

 const groups = [[1, 2, 3, 4 ,5], [2,3]];
 const sets = [...groups];
 
 sets[1].push(9000); // Added a number only to 'sets', not 'groups'
 
 console.log(sets);
 console.log(groups); 
 

This phenomenon appears to occur specifically with arrays within arrays!

What could be causing this issue and how can it be resolved?

Answer №1

The spread operator creates only shallow copies of arrays, meaning that changes made to the copied array will affect the original array as well.

For a deep clone, consider referring to this resource: Deep clone in ES6 using spread syntax (Using JSON.stringify/JSON.parse can serve as an alternative to third-party libraries).

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

Angular 2: Changing HTTP Requests

I am trying to include a single parameter in all my web requests to disable caching forcibly. My goal is to append ?v=1535DC9D930 // Current timestamp in hex to the end of each request. I am coding this in plain ES5 JS, but the documentation is in Types ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Receive real-time price updates from Next.js using GetServerSideProps data

I'm currently working on fetching live bitcoin prices from CoinGecko. In my index.js file, I have an async GetServerSideProps function that is functioning correctly. The returned props are then passed down to the <Home /> component, and subseque ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...

Trouble with activating dropdown toggle feature in Bootstrap 5

I recently upgraded to Bootstrap 5 and now my code is not functioning properly. <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria- controls="navbarCollaps ...

Iterate through an Array of Objects and exhibit a single object property in HTML one at a time by utilizing Javascript

I am working with an array of objects that contain two properties: "quote" and "author". I have a container div where I want the quotes to be displayed one by one at an interval of every 2 seconds. Currently, it is showing one letter at a time instead of d ...

Having difficulty invoking JavaScript code from PHP

When a button is clicked, this Javascript function is triggered: var xmlhttp; function register() { xmlhttp=GetXmlHttpObject(); alert("pass"); if(xmlhttp==null) { alert("Your browser does not support AJAX!"); return; ...

Determine whether a variable is defined following the keyup() event in jQuery

I am currently working on creating a registration form using the keyup() function in JQuery. For instance, when the input is correct, I assign it to a variable called txtuname. After pressing the register button, I need to ensure that all form variables ...

What is the most effective way to rearrange an array so that the maximum number of integers can be placed where smaller integers previously existed?

I'm attempting to grasp the reasoning behind the solution to an algorithmic or logical problem. The problem description is as follows: Given an array of integers, Vasya can rearrange the order of the integers. His goal is to maximize the number of i ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Can the name of the Grunt task target be utilized within attributes?

I have implemented the grunt-replace task to make some content changes in the index.html file. However, I am looking for a way to avoid repeating code unnecessarily. The code snippet below is just an example of what I am trying to accomplish: replace: { ...

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

Perform a jQuery AJAX GET request while passing the current session information

Is it possible to retrieve the HTML content of another webpage using jQuery, particularly when that page is already signed in? In simpler terms, can we use $.get() to fetch a different page on the same website and transfer the PHP/Javascript cookies with ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

Retrieving XML using JavaScript with AJAX

Having trouble retrieving XML data using JavaScript and Ajax. The script takes too long (up to 45 seconds) to collect the data from the database and return it as XML. Everything works fine when loading the data locally, so no issues with cross-domain. An ...

Is there a way to determine the currency symbol based on the information provided by ipinfo?

Currently, I am utilizing JavaScript to obtain the currency symbol based on the information provided by ipinfo. I have successfully retrieved the countries' names and other details using the code below. However, I am now faced with the challenge of ut ...

AngularJS: Component fails to load controller

I am managing a directory structure that looks like this --- js/app.js ------- components ----------- header -------------- headerComponent.html -------------- headerComponent.js -------------- headerController.js Within index.html, I have the following ...

Utilizing the random function in a loop can result in unpredictable and unexpected values

Why is it that I get numbers ranging from 17 to 70,000 in the three console.log statements? However, in the loop, y always seems to fall between 200 and 800. Why is that? console.log("RND " + Math.floor(Math.random()*5000)*17) console.log("RND " + Math ...

Problem encountered while using AJAX to load a PHP script, triggered by an onclick event;

My expertise lies in HTML, CSS, JavaScript, and PHP. However, I find myself lacking in knowledge when it comes to jQuery and Ajax. While I work on web design projects involving bars and nightclubs that prioritize style over performance, my current job dema ...

Ways to display spinner animations during image loading on Next.js?

Currently, I am attempting to implement a spinner display while images are loading on a Next.js website. To achieve this, I am utilizing the NextUI UI library. My website features several cards, and my goal is to showcase a spinner during the image loadin ...