It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot determine the reason behind this unexpected behavior.

var particles = []
var particlesCopy = []

function calculateInitialPositions(){

  for (var i = 0; i < pixels.length; i+=4) {
    if (pixels[i] == 0){
      var x_ = i  % width
      var y_ = i / width / 2
      var coords_ = {x : x_ , y : y_}
      particles.push(coords_)
    }
  };
}

function setup() {  
  loadPixels()
  calculateInitialPositions();
  particlesCopy = [...particles]
}

function draw() {
  for (var i = 0; i < particlesCopy.length; i++) {
    particlesCopy[0].x = 99
  };
  console.log(particles[0].x)
}

The console now prints 99

Answer №1

In Javascript, the = operator assigns Objects, including arrays, by reference rather than by value. This means that when you write:

particelsCopy = particels

You are essentially making particelsCopy point to the same array as particels. They are not two separate arrays. To create a true copy of the array, you need to do it like this:

particelsCopy = particels.slice();

Keep in mind that this is a shallow copy, so if the array contains objects or arrays, they will still be copied by reference. You would have to repeat this process for nested items (e.g., the coords_ object). If dealing with objects, use the pattern

copy = Object.assign({}, original);
.

To make a deep copy of everything by value, you'll have to recursively perform this on each level of nested objects/arrays. Many libraries, such as jQuery, offer pre-built functions to help achieve this.

Answer №2

Utilizing destructuring enables you to duplicate objects within an array

particlesCopy = particles.map(obj => ({...obj}));

Answer №3

When you see the line:

particelsCopy = particels

It's important to note that this code snippet is actually creating a copy of the array reference, not the individual elements within the array.

To truly create a separate copy of the array with its elements, you'll need to allocate a new array object and then copy over each element individually. If the elements themselves are objects, you may also need to make sure you're making a shallow or deep copy of them as well. One way to achieve this is by using Object.assign() to create a shallow copy.

particelsCopy = [] // assuming this step has already been done
for (var i=0; i<particels.length; i++){
   particelsCopy[i] = Object.assign({}, particels[i]};
}

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

Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far: <script> var margin = { top: 20, right: 80, bottom: 20, left: 50 }, width = $("#trendc ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

Developing a matrix arithmetic parser using JavaScript

Currently, I am in the process of developing a program that can solve matrix equations. My main focus right now is on making sure the parser functions correctly. However, I am feeling lost and unsure of where to begin. In my program, I utilize an array of ...

"Enhance your website with the powerful autocompletion feature of

I am using Zend Framework to create a form element that utilizes Zend_Dojo_Form_Element_ComboBox. By setting dojox.data.QueryReadStore as the store type, I am able to generate a list of selectable values in my HTML input field. This allows me to either cho ...

Exploring the elements of an array in Python

I'm in the process of developing an iterator class for my custom array-based class. This class functions like a regular array but includes methods for inserting elements into it. I've been able to find examples of iterators for linked lists, but ...

Expanding size on hover without affecting the alignment of surrounding elements

Imagine there are 10 divs on the page styled as squares, collectively known as the home page. Among these 10: 3 divs belong to the .event1 class, 5 divs belong to the .event2 class, and 2 divs belong to the .event3 class. <div class="boxes event1"> ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...

Disabling iframe javascript timers when iframe is no longer in the user's view

Currently, I am working on a blog post that will showcase various HTML5/Javascript animations through multiple <iframe> sections. These animations utilize methods such as requestAnimationFrame() and/or setInterval(). Due to limitations within the blo ...

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...

Sending a request in Vue.js and not receiving a defined response

As a beginner in VueJs and Expressjs, my goal is to create the frontend using Vuejs and backend using ExpressJs. When I send a post request to the backend (ExpressJs), I encounter the following issues: 1- Response from the server is undefined. 2- In Chrom ...

React: The issue with async and await not functioning as expected when using fetch

I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...

Utilizing Node.js, delete the author from the database and then use a GET request to display all

Exploring node and express for the first time. I've been working on an example that utilizes GET and POST methods, but now I want to implement DELETE function to delete a book based on its title. Additionally, I need to introduce another GET method to ...

What are some ways to prevent manual page reloading in Node.js when using EJS?

Currently, I am utilizing Node as a server and frontend in EJS. My project involves working with socket.io, which is why it is essential that the page does not refresh manually. If a user attempts to reload the current page, the socket connection will be d ...

Implementing a feature to automatically set the datepicker value to the selected date upon page initialization

I am working with a datepicker element, identified by id="from_dt", and a button with id="fromToDate". When a date is selected from the datepicker and the button is clicked, the page will load. At that point, I want to transfer the selected date to a textb ...

Having trouble setting up the next-auth login page and experiencing issues with the getProviders() function

Greetings to all fellow web developers, I am currently working on a Next.js application that utilizes next-auth for user authentication. I have set up the [...nextauth].js file in the "pages/api/auth" directory and a signin.js file in the "pages/auth/" di ...

Do all descendants consistently trigger rerenders?

Recently, I was exploring the React new documentation here, where I came across this interesting piece of information: The context value mentioned here is a JavaScript object with two properties, one being a function. Whenever MyApp re-renders (for examp ...

Text will split into two at a later time

I am using the material-ui library. Curious about adding a text followed by a line divider. Here's how I attempted it: <Grid> <Typography variant="h6" color="primary"> {'text'} </Typograph ...

Could someone clarify the specific workings of the Google V8 bytecode related to the creation of object literals

Check out this awesome piece of JavaScript code! const person = { name: 'John', age: 30 }; console.log(person); Here's the Google V8 byte code generated by using node js option --print-bytecode. [generated bytecode for function:] ...

Customize the icon used for expanding and collapsing in AngularJS

I want to modify the icon (e.g., plus, minus) when clicking on an expand-collapse accordion. Currently, I am using the Font Awesome class for icons. While I know it can be easily achieved with jQuery, I'm wondering if there is a way to do this in Angu ...

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...