Creating a duplicate of a JavaScript array within a class prototype method

I have been working with a JavaScript class:

function Node(board,x,y,t){
    this.board = board;
    this.x = x;
    this.y = y;
    this.playerTile = t;
    this.oponentTile = getOponentTile(this.playerTile);
    this.parent = null;
    this.getChildren = getChildren;

};

In my code, there is a function where I copy the content of this.board array into a new variable called tempBoard using slice()

var getChildren = function() {
        if(this.x==-1 && this.y ==-1){
            var moves = getAllValidMoves(this.board,this.playerTile);
        }
        else{
            var tempBoard = this.board.slice();
            makeMove(tempBoard,this.playerTile,this.x,this.y);
            var moves = getAllValidMoves(tempBoard,this.playerTile);
        }

        var children = [];
        for(var i = 0;i<moves.length;i++){
            var currentMove = moves[i];
            var currentBoard = this.board.slice();
            if(this.x==-1 && this.y ==-1){
                children.push(new Node(currentBoard,currentMove[0],currentMove[1],this.playerTile));
            }
            else{
                makeMove(currentBoard,this.playerTile,this.x,this.y)
                children.push(new Node(currentBoard,currentMove[0],currentMove[1],this.oponentTile));
            }

        }
        return children;
    };

The issue arises when makemove() is invoked, both tempBoard and this.board are being altered.

Is there a way to duplicate an array without affecting the original one?

Answer №1

.slice() creates a shallow copy of the array, not a deep copy.

This means that when you use .slice() on an array of objects to make a copy, it produces a new array that is only one level deep. The new array still references the same objects as the original array. You can manipulate the copied array without affecting the original one or vice versa.

However, if you modify the objects within the array, these changes will be reflected in both arrays since they share the same object references. To create a completely independent copy of the array and its contents, you need to perform a deep copy, which can be more complex depending on the array's structure.

There are various methods for creating deep copies, and you can explore them further through the following resources:

How do I correctly clone a JavaScript object?

Copying an array of objects into another array in javascript (Deep Copy)

Copying array by value in JavaScript

If your array does not contain circular references (where objects point back to themselves), a simple method to create a copy is using:

var tempBoard = JSON.parse(JSON.stringify(this.board));

Answer №2

potentially beneficial

function duplicate(data){
    let outcome = JSON.stringify(data);
    return JSON.parse(result);
}

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

Transferring information about service events to a controller in Angular

I am facing an issue with some audio elements in my service that listen for the "ended" event. I am looking for a way to pass this message to an angular controller. Currently, my service code looks like this: Audio.addEventListener "ended", (-> ...

Cleaning arrays in Angular 2 forms: A step-by-step guide

Need some assistance. I'm developing an app in Angular2(4) which includes a Form with 2 select boxes and 1 checkbox. My goal is to establish a dependency between these boxes using the following array: dataJSON = [ { productName: 'Produ ...

What causes a string of numbers to transform into a string when used as an array key?

$arr['123'] = "test"; var_dump($arr); // Key is int $arr2['123a'] = "test"; var_dump($arr2); //Key is string Can anyone explain why this behavior is occurring? Is there a solution for setting a key as a string rather than a ...

The jQuery function .val()/.text() is unable to retrieve information from a particular section of HTML

Implementing HandlebarsJS with PHP and Yii to generate a page. Here is a snippet of the html/handlebars code on the page {{#if embed_link}} <p class='f_hidden_p'> <a href='{{embed_link}}'> {{ ...

Convert the HTML content into a PDF while retaining the CSS styles using either JavaScript or Django

Looking to create a PDF of an HTML element with background color and images. Seeking a solution, either client-side or server-side using Django/Python. Tried jsPDF on the client side, but it does not support CSS. Considering ReportLab for Django, but uns ...

Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method. The issue arises when attempting to make a DELETE request using axios, resulting in a Request ...

Dot/Bracket Notation: flexible key assignments

I have an item that contains various image URLs accessed through data[index].gallery.first.mobile/tablet/desktop "gallery": { "first": { "mobile": "./assets/product-xx99-mark-two-headphones/mobile/image-gallery-1.j ...

Discovering React Flowtype's Node.contains() event target

In my React code, I have set up an event listener like this: document.removeEventListener("mouseup", this.handleDocumentClick); I found the definition of the method in Flow's source code, and it looks like this: removeEventListener(type: MouseEvent ...

When loading HTML using JavaScript, the CSS within the HTML is not properly processing. Leveraging Bootstrap 5 might help resolve

Currently utilizing bootstrap 5 for my project. I have a setup in index.html where I am loading the contents of nav.html using JavaScript. However, I am facing an issue wherein the CSS styling for the navbar is not being applied when loaded via JS. Strange ...

Use the addition operator on a subclassed array

I attempted to merge two subclassing arrays together. However, it seems to be returning an Array class instead of MyArray. class MyArray < Array end foo = MyArray.new bar = MyArray.new p foo.class #=> MyArray p (foo + bar).class #=> Array What ...

Error encountered: When implementing mergeImages in express.js, a ReferenceError occurs stating that the window is not

I am encountering an issue while using mergeImages on my express.js server. The error message "ReferenceError: window is not defined" is displayed, but I am puzzled because I have not used the word 'window' in my code at all. Could you please rev ...

Input new information into the Google Spreadsheet Database

I am currently working on updating and adding data to a Google spreadsheet that will serve as a database. Take a look at my spreadsheet here along with my JSfiddle link. While I have managed to retrieve information using the fiddle, I am facing challenges ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

How to encode a binary file to base64 and add it to formdata using Node.js

Question: I currently have a code snippet in my NextJS API that is used to manipulate images on canvas using node-canvas before sending them to another API for additional processing. /* At sample.js in NextJS API */ import axios from 'axios'; im ...

MongoDBError: Unauthorized access attempt for [action] operation by the user is prohibited

I've been struggling with this error for quite some time now, attempting all the recommendations on this forum without success. My goal is to develop a website where users can register and their credentials are saved in a database. Below is a snippet ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Chips Style Vuetify Autocomplete Menu / Dropdown Feature

I am looking to change the appearance of the items in the dropdown menu of my Autocomplete Box. Vuetify-Autocomplete Currently, it displays the standard style for each item: Current <v-autocomplete chips deletable-chips multiple v-model="selectedT ...

JavaScript loop not functioning properly to show modals when button is clicked

I successfully created a Javascript function to display a modal on button click, but I realized that I would have to manually repeat the code 56 times. Instead, I attempted to write a loop to automate this process, but unfortunately, the new function is no ...

Extract a value from a json document

Hey there! I'm looking to create an unwhitelist command. When a user is mentioned or their ID is provided, I want it to be removed from the JSON file without checking if the ID exists. Do you have any suggestions on how to accomplish this? Here is my ...

Performing multiple SQL queries in a for loop using Node.js and Express

After submitting a Post form, I receive a req.body containing multiple values in the following format: console.log(req.body) { productid:[1, 2, 3] qty: [3, 5, 6] } I'm trying to implement a for loop to use these values in SQL queries. However, I e ...