The slice method for copying arrays seems to be malfunctioning

It's perplexing that even after utilizing distances.slice(), I end up modifying the original array when I make changes to the new copy. What could be causing this unexpected behavior?

var distances = [
  ['-1', '10', '-1', '31'],
  ['10', '-1', '10', '-1'],
  ['-1', '-1', '-1', '10'],
  ['15', '6', '-1', '-1']
];
for (var i = 0; i < 4; i++) {
  console.log(distances, 'distances pairstop');
  var sampleDistance = distances.slice()
  sampleDistance[0][2] = ['fooo']
}

Answer №1

When using the slice method in JavaScript, it creates a shallow copy of the array as stated in the documentation:

The slice() function makes a shallow copy of a part of an array and creates a new array object with elements selected from a starting point to an end point (excluding the end point). The original array remains unchanged.

Since the variable distances is an array of arrays, the variable sampleDistance will also be a shallow copy. This means that both variables reference the same one-dimensional arrays within the two-dimensional array. When you make changes like sampleDistance[0][2] = ['fooo'], it affects both variables since they point to the same data.

This could potentially lead to bugs in your code due to the shared references between the arrays.

Answer №2

If you want to duplicate an array that contains sub arrays of unknown depth, a versatile array duplication method is required like the following:

Array.prototype.duplicate = function(){
  return this.map(element => Array.isArray(element) ? element.duplicate() : element);
};

Simply using distances.duplicate() will accomplish the task seamlessly.

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 getter method in the Vuex store object seems to be returning varying values when accessing nested properties

Currently, my Vuex store is being used to store a user object. This code snippet is a getter function for the user object: getters: { user: (state) => state, isAuthenticated: state => { console.log("user object", state); ...

What is the most effective method for implementing grid-based scrolling in a top-down RPG game?

In my browser-based application, which is currently built using PHP, JavaScript, HTML5, and jQuery as the only framework, I have a question regarding image scrolling. If I have enough 64x64 images to fill up my screen about 100 times, what technique would ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

Creating Angular UI states with parameters in TypeScript

My Understanding In my experience with TypeScript and angular's ui state, I have utilized "type assertion" through the UI-Router definitely typed library. By injecting $state into my code as shown below: function myCtrl($state: ng.ui.IStateService){ ...

Employing selenium.isElementPresent in Selenium 1 does not have the capability to identify an element that is dynamically added to the Document Object Model (

After trying out various locators, I have yet to find one that can detect an element that was added to the DOM. Below is my latest attempt at solving this issue: selenium.fireEvent("//button[2]", "click"); waitUntil(new Condition() { @Override pu ...

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

The use of jQuery for fetching posts via ajax can lead to a crash in the browser

I have a social media platform where I implemented jQuery on the main feed page. The jQuery is set up so that as users scroll down, the next batch of posts is fetched using ajax and added to the DOM. However, after a few ajax requests, the browser slows do ...

Unable to retrieve class attributes within a function

I have recently started delving into the world of node.js, and I am facing some challenges with a middleware that I created. The purpose of this middleware is to act as an Error handler. However, I am encountering difficulties in accessing properties that ...

Display modal popup only once the dropdown has been validated, with the validation focusing on criteria other than the dropdown itself

Looking for a way to validate dropdown values. Popup should only show if the dropdown values are selected; otherwise, the popup should remain hidden. Below is the code snippet: <div class="main-search-input-item location"> ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

Refresh the page only when on the initial page of the pagination

I've been utilizing this jQuery code with AJAX for pagination purposes. Currently, I am fetching data from a PHP file that displays limited information. Here is the index file snippet: <script type="text/javascript"> $(document).ready(fun ...

Scrolling causes a fade effect with the opacity value adjusting

Can someone help me with my script? jQuery(document).ready(function(){ jQuery(window).scroll(function () { var scrollTop = jQuery(window).scrollTop(); var height = jQuery(window).height(); jQuery('.background_top_dis ...

Ways to Determine if a User Has Closed the Page

How can I detect when a user closes the page without using the back button or typing in a different URL in the address bar? I've attempted to use the following code: $(window).bind('beforeunload', function () { logout(); }); This solutio ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

JavaScript: Display all global variables on Internet Explorer

Is there a way to retrieve the instance name of my class without passing it as a parameter? I have tried looping through all global objects and comparing them with the this pointer. This method works in Chrome and Firefox, but not in Internet Explo ...

Javascript Mouse Events Not Functioning Properly with Three.JS Scene Components

Currently feeling quite perplexed (probably due to fatigue from working on this at an inopportune time). I'm in the midst of trying to configure my three.js application to trigger distinct functions based on different mouse events when the cursor hove ...

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimenta ...

Tips for implementing File upload with WEB API in Dot net core

Currently, I am developing an ASP DOT NET core web api that requires sending multiple attachments. My implementation looked something like this: <input type="text" id="txt_firstName" /> <input type="text" id="txt_lastName" /> <input type= ...