Every item in my array is replaced by the most recently added element

Take a look at this code snippet on JSFiddle: https://jsfiddle.net/reko91/998woow6/

The issue I am facing with my project is that every time I add an element to an array, it ends up overwriting all the existing elements with the newly added one.

To replicate the problem, follow these steps:

  • Click on the AddToArray button, which adds the current values of nodes and edges into an object and then pushes that object into the thisArray array.

  • Next, click on either DeleteNodes or DeleteEdges to remove the last element from their respective arrays.

  • Finally, press the AddToArray button again to add the updated nodes and edges into a new object, but you'll notice that the original object (at index 0) gets replaced by this new object.

I've tried researching online and suspect that closures might be causing this issue, but I'm unable to resolve it yet.

If you prefer viewing the code here, here it is:

var thisArray = [];

            var nodes = [1, 2, 3, 4, 5];
            var edges = [1, 2, 3, 4, 5];

            function addToArray() {
                var thisData = {
                    nodes: nodes,
                    edges: edges
                }
                thisArray.push(thisData)
                console.log('thisArray')
                console.log(thisArray)
            }

            function deleteNodes() {

                nodes.pop();
                console.log(nodes)
            }

            function deleteEdges() {

                edges.pop();
                console.log(edges)
            }
<button onclick='addToArray()'>
                AddToArray
            </button>

            <button onclick='deleteNodes()'>
                Delete Nodes
            </button>

            <button onclick='deleteEdges()'>
                Delete Edges
            </button>

Answer №1

The reason this is happening is because you are assigning a reference to an array, causing each object to point to the same array. To resolve this, use the slice method to create a clone of the array:

function addToNewArray() {
  var newData = {
    elements: elements.slice(),
    items: items.slice()
  }
  newArray.push(newData)
  console.log('newArray')
  console.log(newArray)
}

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

The "next" button on my carousel is unresponsive and the automatic transitioning feature is not working

I'm having trouble implementing a carousel on my website. The next/previous buttons and automatic slides are not functioning properly. <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!- ...

Changes in React BrowserRouter URLs are not reflected on the page or components, requiring a manual refresh for them to

Greetings, fellow developers! I have developed an app using React with a remote menu component. Despite trying numerous techniques, I am facing an issue where my URL changes but the components are not rendering on the screen. You can check out the code h ...

Employ a class function within router.get

I'm a beginner with node.js and I'm running into an issue when trying to use a class method in the router.get callback function. Can someone assist me with this problem? Route.get() is expecting a callback function but received a [object object] ...

MUI: reveal multiple selection when hovering & prevent dropdown from moving around

Utilizing material ui, I am facing two issues with a multiple select component that I cannot seem to resolve: While selecting an item, the dropdown moves around (I have already attempted solutions like MenuProps={{ variant: "menu", getContentAnc ...

Exploring the concept of ng-model with undefined values in AngularJS

Having an input with a $watch function that updates a search query in real time through AngularJS, I am encountering an issue. Despite setting the initial value of the model to empty, it automatically triggers the search and displays results. My concern i ...

Notification of array being converted to a string

I'm encountering a puzzling notification on the specific line of code below: $this->$aStyles = $aStyles; This particular code snippet is within the following function: private function cleanStyles() { if ((isset($this->sValue))&&( ...

Create geometric shapes on Google Maps version 2

Can anyone guide me on how to draw a polygon on Google Maps with user-input coordinates? I have two input fields for latitude and longitude, and when the user clicks the button, I want the polygon to be drawn. The code I currently have doesn't seem to ...

AngularJS - Creating a dynamic wizard experience using UI-Router

I have set up my routes using ui-router in the following way: $stateProvider .state('root', { url: "", templateUrl: 'path/login.html', controller: 'LoginController' }) .state('basket&a ...

What is the proper way to handle postMessage events from a Streamlit iframe within a Next.js app?

I'm currently in the process of integrating a Streamlit app into a Next.js application by embedding the Streamlit within an iframe. My main goal is to send data from the Streamlit app to the Next.js parent using window.postMessage, specifically focusi ...

Selecting the content within a table to easily edit it

I am working on a project where I have a table filled with data fetched from a database. My goal is to allow users to click on a cell in the table, make changes to its content, and then save those changes back to the database. Below is the code snippet I a ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...

Unusual escape_javascript quirk witnessed in Ruby on Rails

Once the ajax method is called, the escape_javascript function starts outputting </div> </div> </div> for each rendered item. Despite thoroughly checking all closing tags multiple times, I can't seem to identify any errors. Could thi ...

Entering a value into an HTML textbox using Awesomium in VB.NET

This code snippet is used to split text from a listbox: For Each Item As Object In ListBox1.SelectedItems TextBox2.AppendText(Item.ToString + Environment.NewLine) Next Dim str As String = TextBox2.Text D ...

Every time I attempt to run "npm install" on Visual Studio Code, I encounter an error

Every time I try to run npm install, I encounter this error. My node version is 18.9.1 and I have exhausted all possible solutions. Any help would be greatly appreciated. '''npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Us ...

Executing several Ajax requests at once can decrease the speed of the process

When I make simultaneous API calls using Ajax, the process seems to be slow as JavaScript waits for all API responses instead of fetching them asynchronously. For instance, /api/test1 usually responds in 5 seconds and /api/test2 also responds in 5 seconds ...

fresh map from Google: Coordinates LatLng may not be a number, but my hunch tells me it is

Seeking Assistance with this Issue - For example, the initial location data appears as: "Object Lat: -36.768498 Lng: 174.75895" However, an error is indicating that the latitude is not recognized as a number. Rather than making adjustments without clea ...

Create a file with jQuery and send it to PHP

Hello everyone, I am currently in the process of developing a website that has the ability to generate an MS Excel file using jQuery and allow users to download it. My question is, how can I pass this generated file to PHP so that it can be sent as an atta ...

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

Tips for verifying blank form fields

Is there a way to validate empty form fields before submission and show an alert? This validation is important as some fields are hidden using v-show. Here is an example: <!DOCTYPE html> <header> <script src="https://unpkg.com/vue@n ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...