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

"Exploring the power of JQuery in adding new elements and accessing the newly appended

I have a code that appends some HTML to a div using JQuery like this: $("#divId").append("<div class='click' data-id='id'></div>"); and I want to access the appended div by clicking on it like so: $(".click").click(functi ...

Utilizing JSON.stringify with variables and arrays

Here's the code snippet I'm working with: var dictionary = "["; for (var i = 0; i < aElem.length; i++) { dictionary += "{Key:" + aElem[i].value + ",Value:" + bElem[i].value + "}" if (i < aElem.length - 1) di ...

JavaScript framework that is easily customizable to include support for XmlHttpRequest.onprogress, even if it needs to be emulated

Which JavaScript library or framework offers support for the "onprogress" event for XmlHttpRequest, even if it needs to be emulated using a plugin or extension? Alternatively, which JavaScript framework is the most straightforward to extend in order to add ...

The component is no longer able to locate the imported element when it is being shared

Recently, I imported a component into the shared module in order to use it across 2 different modules. However, upon recompiling the app, an error message appeared stating that the jodit-editor, which is utilized by the shared component, is not recognized ...

Oops! An unexpected field was encountered while trying to use the uploadMultiple function from dropzone.js

I was looking for a way to allow users to select images to accompany their reviews. That's when I came across dropzone.js. However, I encountered an issue when trying to send multiple images in one request. I expected the req.files to contain an arra ...

Using JavaScript, generate an array of objects that contain unique values by incrementing each value by 1

I have an array of objects called arrlist and a parameter uid If the property value has duplicate values (ignoring null) and the id is not the same as the uid, then autoincrement the value until there are no more duplicate values. How can I achieve the a ...

The concept of navigation and passing parameters in Angular.js

Attempting to customize the standard user module of MeanJS, I added a new route: state('users', { url: '/users/:username', templateUrl: 'modules/users/views/view-profile.client.view.html' }); ...

Having trouble retrieving data from the database when passing input to a mongoose query using an href tag in Node.js

Welcome to My Schema const AutomationSchema=new mongoose.Schema( {EventName:String, EventDate:String, EventLocation:String, EventDetails:String } ) The Events Model const EventsModel=new mongoose.model("Events",AutomationSchema ...

Navigating between different components in React Router V4 allows for seamless transitions without having to reload the

I am currently learning React with React Router V4 and I have a specific scenario in mind that I would like to achieve, possibly illustrated by the image below: Click on the "Next" button Trigger a click event to Component A ("button got clicked") Upon c ...

What is the best way to patiently wait for lines to be printed out one by one

I am in the process of creating my own personal website with a terminal-style design, and I'm looking to showcase a welcome banner followed by a welcoming message. The effect I have in mind involves lines appearing individually from top to bottom and ...

Ways to extract the source code of a webpage that has been modified on load

While working on extracting data from a website (completely within legal boundaries), I encountered an interesting situation. This particular site has 5 questions with answers on each page. However, upon inspecting the source code by pressing Ctrl+U, I no ...

Calculate the sum of elements in an array based on a condition provided in a different

Looking for help with summing an array based on conditions in another array using Python. sum=0 for i in range(grp_num): if lower_bounds[i] > 0: sum = sum + histo1[i] I was thinking the numpy equivalent would be np.where(lower_bounds>0, ...

Link a distinctive number to a specific element

I am searching for a method to link a DOM element with a distinct number that is not assigned to any other element in the DOM. Using an Id attribute is not an option as not all elements possess such an identifier. One potential approach is to obtain a num ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Only switch a radio button when the Ajax call results in success

Within an HTML form, I am working with a group of Radio buttons that trigger an Ajax call when the onchange() event is fired. This Ajax call communicates with the server to process the value sent by the call. The response can either be a string of "succes ...

How can I efficiently utilize HTML/CSS/JS to float items and create a grid that accommodates expandable items while minimizing wasted space?

After meticulously configuring a basic grid of divs using float, I've encountered an issue. When expanding an item in the right-hand column, the layout shifts awkwardly. My goal is to have boxes A and B seamlessly move up to fill the empty space, whi ...

Tips for refreshing information in the Angular front-end Grid system?

I am currently working with the Angular UI Grid. The HTML code snippet in my file looks like this. <div ui-grid="gridOptions"></div> In my controller, I have the following JavaScript code. $scope.values = [{ id: 0, name: 'Erik&a ...

Adding Empty Space Following Error Message in Codeigniter

I am encountering an issue with my code where there is a blank space appearing after the error message. Here is the code snippet that is causing the problem: <script> const successNotification = window.createNotification({ theme: 'error&a ...

What are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...