Array.from does not create a deep copy

I'm in the process of creating my own Battleship game, and I've been researching for about 10 hours but haven't been able to crack it yet.

The issue I'm facing is related to making a deep copy using Array.from; whenever I modify the plateauAfter array, it also alters the plateauBefore array.

//function to create a two-dimensional array
function plateau() {
let grid = new Array();
    for (let i = 0; i < 10; i++) {
        grid[i] = new Array();
        for (let j = 0; j < 10; j++) {
            grid[i][j] = '[]';enter code here
        }
    }
    return grid;
}


let CPU = {
    ships: [
        {
            AircraftCarrier: 5,
            Position: ['B', 3],
            Direction: 'down',
            Symbol: '[P]'
        },
        {
            Submarine: 4,
            Position: ['D', 1],
            Direction: 'right',
            Symbol: '[S]'
        },
        {
            Frigate: 3,
            Position: ['E', 4],
            Direction: 'left',
            Symbol: '[F]'
        }
    ]
}

function placeShip(grid, shipType, position, direction, symbol) {

    let plateauBefore = Array.from(grid);
    let plateauAfter = Array.from(grid);

    let letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
    let row = position[1] - 1;
    let column = letter.indexOf(position[0]);

    for (i = 0; i < shipType; i++) {

        if (-1 in plateauAfter[row]) {
            console.log('The ship exceeds the grid! Please try again.');
            return plateauBefore;
        } else {
            switch (direction) {
                case 'up':
                    try {
                        plateauAfter[row - i][column] = symbol;
                        break;
                    } catch (error) {
                        console.log('The ship exceeds the grid! Please try again.');
                        return plateauBefore;
                    }
                case 'down':
                    try {
                        plateauAfter[row + i][column] = symbol;
                        break;
                    } catch (error) {
                        console.log('The ship exceeds the grid! Please try again.');
                        return plateauBefore;
                    }
                case 'left':
                    try {
                        plateauAfter[row][column - i] = symbol;
                        break;
                    } catch (error) {
                        console.log('The ship exceeds the grid! Please try again.');
                        return plateauBefore;
                    }
                case 'right':
                    try {
                        plateauAfter[row][column + i] = symbol;
                        break;
                    } catch (error) {
                        console.log('The ship exceeds the grid! Please try again.');
                        return plateauBefore;
                    }
            };
        }
    }
    return plateauAfter;
}

let gridCPU = plateau();

gridCPU = placeShip(gridCPU, CPU.ships[0].AircraftCarrier, CPU.ships[0].Position, CPU.ships[0].Direction, CPU.ships[0].Symbol);
gridCPU = placeShip(gridCPU, CPU.ships[1].Submarine, CPU.ships[1].Position, CPU.ships[1].Direction, CPU.ships[1].Symbol);
gridCPU = placeShip(gridCPU, CPU.ships[2].Frigate, CPU.ships[2].Position, CPU.ships[2].Direction, CPU.ships[2].Symbol);

console.log(gridCPU);

Answer №1

To improve performance, you can try duplicating the array using ES6 array spread method like so:

let originalArray = [...arrayToDuplicate];
let duplicatedArray = [...arrayToDuplicate];

Alternatively, you can use Array.concat if compatibility with older JS versions is a concern:

let originalArray = [].concat(arrayToDuplicate);
let duplicatedArray = [].concat(arrayToDuplicate);

Answer №2

I stumbled upon the solution here : This method works perfectly for deep copying arrays and objects!

//Deep Clone
let original = [{ x:{z:1} , y: 2}];
let copy = JSON.parse(JSON.stringify(original));
copy[0].x.z=0
console.log(JSON.stringify(original)); //[{"x":{"z":1},"y":2}]
console.log(JSON.stringify(copy)); // [{"x":{"z":0},"y":2}]

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

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Ways to structure this updateone query for mongoose formatting

UPDATE: After making adjustments to the query using arrayFilters recommended by someone here, the query is returning success. However, the values in the database are not being updated. I am attempting to update specific fields within a MongoDB collection ...

The spinner persists even after the fetch api call

The issue I'm facing with my song lyrics app is that the spinner does not disappear after fetching data from the API. It seems like JavaScript is unable to detect the presence of the spinner even though it exists when the remove function is called. I ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

If I click on the datalist link option during an ajax append, I would like to be redirected

When I try to link after clicking an option in the appended AJAX, it does not seem to work as expected: More details: $('#input-friends').on('input', function () { var id = $('#input-friends').val(); $.ajax({ ...

Utilizing $asyncValidators in angularjs to implement error messages in the HTML: A guide

This is my first major form with validations and more. I've set up a Registration form and I'm utilizing ng-messages for validation. The issue arises when I have to check the username, whether it already exists in the JSON server we are using or ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...

"Transforming a static navbar to a fixed position causes the page to jump

Having some difficulty figuring this out. I'm working on a bootstrap navbar that transitions from static to fixed when the user scrolls past the logo at the top. Everything seems to be working fine, except for when the navbar reaches the top, it sudde ...

The function does not provide an output of an Object

I have two JavaScript classes, Controller.js and Events.js. I am calling a XML Parser from Events.js in Controller.js. The Parser is functioning but not returning anything: SceneEvent.prototype.handleKeyDown = function (keyCode) { switch (keyCode) { ...

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...

The information retrieved from the database query is failing to appear on my webpage

I am encountering an issue where I am unable to display product details on my webpage in a specific format after submitting an ID number through a form. The query does not show any data when submitted. My objective is to append the latest retrieved data be ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

Catalog of items in Mustache

I am currently working on generating HTML content using the mustache template engine. However, I have encountered an issue when trying to render a list of objects. Below is an example of my object: var Prod={ "Object1": { "name": "name1", "cat ...

Alter the Cascading Style Sheets (CSS) value by accessing a

I have two files, keyboard.css and keyboard.js. My objective is to modify a CSS rule: .ui-keyboard div { font-size: 1.1em; } Is there an alternative method to change the font size without utilizing $(".ui-keyboard div").css()? I want the modification ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Tips for showing HTML content in an Angular UI grid

I've been attempting to showcase HTML within the grid by checking out this resource: Add html link in anyone of ng-grid However, my attempts led me to this code snippet: var app = angular.module('myApp', ['ngGrid']); ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

The EJS is throwing an error because it cannot define the property "round" on an undefined object

I'm currently delving into the realm of Node.js, using the "Secrets of Ninja" book as my guide. I've come across an EJS program in the book that I copied verbatim to run, but I encountered an error despite not making any modifications to the code ...