Make a copy of an array and modify the original in a different way

Apologies for my poor English, I will do my best to be clear. :)

I am working with a 3-dimensional array which is basically an array of 2-dimensional arrays. My task is to take one of these 2-dimensional arrays and rotate it 90° counterclockwise. Here is an example:

[1|2|3]  
[4|5|6]
[7|8|9]

The rotated version should look like this:

[3|6|9]  
[2|5|8]  
[1|4|7]

In order to modify the original array, I decided to create a copy of it so that I have a reference to work with. Here is what I have attempted:

var temp = [];
var cube = [
    // Arrays representing different elements
];

function CCW() {
    temp = temp.concat(cube[4]);
    for(var i = 0; i < 3; i++)
        for(var j = 0; j < 3; j++)
            cube[4][i][j] =  temp[j][2-i];
}

CCW();

The copied original array should be stored in temp.

The issue arises in this line: cube[4][i][j] = temp[j][2-i];. It not only changes the values in the cube array but also affects the values in temp. I attempted replacing temp = temp.concat(cube[4]); with temp = cube[4].slice(0); without success.

If you could advise me on how to address this problem, I would greatly appreciate it. Thank you all. :)

Answer №1

When you directly assign an array in JavaScript, it is a reference assignment, meaning changes will affect both arrays. To make a copy of an array, the array.slice() function needs to be used.

Note: When dealing with multi-dimensional arrays, a recursive function must be written to properly copy them (e.g. [1, 2, ['some', 'inner', 'array'], 3]).

Does this explanation clarify things?

Edit: Below is a deepCopyArray function that copies arrays, but further expansion is needed for copying arbitrary objects...

function deepCopyArray(arr) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++)
    {
        var a = arr[i], ele;
        if (a instanceof Array) //current element is an array...
            ele = deepCopyArray(a);
        else 
            ele = a;
        newArr.push(ele);
    }
    return newArr;
}

Answer №2

One way to solve this is by using the slice method on the cube array.

You can iterate through each row in a for loop to apply the solution.

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

How can I add a black-colored name and a red-colored star to the Placeholder Star as a required field?

I'm looking to customize the placeholder text in an input field. I want the main placeholder text to be in black and have a red star indicating it's a required field. However, my attempt to set the color of the star specifically to red using `::- ...

How can I effectively exclude API keys from commits in Express by implementing a .gitignore file?

Currently, my API keys are stored in the routes/index.js file of my express app. I'm thinking that I should transfer these keys to an object in a new file located in the parent directory of the app (keys.js), and then include this file in my routes/in ...

How about using a variation of the string within the function?

I'm just starting out in programming (this is only my second question on stackoverflow :-) ). Using a foreach function, I retrieved 5 different string values for $Loncoord, $Latcoord, $gui; which I can see when using print_r as shown below: "-5.6816 ...

How can I change an array from OData into JSON format?

I've been working on finding a solution to properly handle an OData response in JavaScript. The issue I am facing is that the response comes back formatted as an array rather than JSON, preventing me from using JSON.parse(mydata) with the current data ...

Customizing HTML list headers using an external JavaScript function

Hi everyone, I've been working on a login page and I want to enhance the user experience by displaying the logged-in user's username at the top of the screen, which can then trigger a dropdown list upon clicking. To achieve this, I've writt ...

Create a discord.js bot that can randomly select and send a picture from a collection of images stored on my computer

I'm currently working on a bot that sends random pictures from an array of images stored on my computer. However, I encountered an issue when trying to embed the image, resulting in the following error message: C:\Users\47920\Desktop&bs ...

What is the most efficient way to update all elements within an array in a MongoDB document to a specific value?

Imagine a scenario where I possess the subsequent document: { _id: ObjectId("5234cc89687ea597eabee675"), code: "xyz", tags: [ "school", "book", "bag", "headphone", "appliance" ], qty: [ { size: "S", num: 10, color: "blue" }, ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...

"Seeking clarification on submitting forms using JQuery - a straightforward query

My goal is to trigger a form submission when the page reloads. Here's what I have so far: $('form').submit(function() { $(window).unbind("beforeunload"); }); $(window).bind("beforeunload", function() { $('#disconnectform&apo ...

JavaScript has been used to modify a cell's URL in jqGrid

Currently, I am utilizing struts2-jqgrid along with JavaScript. After the jqgrid has finished loading, it retrieves <s:url var="updateurl" action="pagosActualizar"/>. Subsequently, in the HTML view source, jqgrid generates options_gridtable.cellurl = ...

ClickAwayListener doesn't function correctly when used in conjunction with Collapse or Fade animations

Currently, I am working on implementing a notifications area on my website. The idea is to display a notification icon, and once the user clicks on it, a list of notifications will be shown. For reference, you can view the code in this codesandbox I have ...

I'm looking for ways to incorporate TypeScript definition files (.d.ts) into my AngularJS application without using the reference path. Can anyone provide

I'm interested in leveraging .d.ts files for enhanced intellisense while coding in JavaScript with VScode. Take, for instance, a scenario where I have an Angular JS file called comments.js. Within comments.js, I aim to access the type definitions prov ...

Iconic Side Navigation with collapsed button malfunctioning due to negative positioning

I'm facing two issues with my webpage. First: I have three buttons on the right side of my page that are supposed to behave like the buttons on this example. However, when you scroll, you can see that their position is incorrectly displayed "outside" ...

Creating dynamic and engaging animations for components using ReactCSSTransitionGroup

I'm currently attempting to add animation to a modal that appears when a button is clicked using ReactCSSTransitionGroup. The modal is showing up on button click, however, there is no transition effect. My render method is set up like this: render() ...

Challenges with Organizing Data and Maintaining Database Integrity

I have been working on making this sortable code function properly. Initially, I had it working fine with <li> elements as shown in the UI examples. However, now I am trying to implement it with <div> elements. While it shouldn't be much o ...

Issues with Angular displaying filter incorrectly

Whenever a user chooses a tag, I want to show only the posts that have that specific tag. For instance, if a user selects the '#C#' tag, only posts with this tag should be displayed. This is how my system is set up: I have an array of blogs that ...

Eliminate HTML field based on checkbox status

I'm looking to dynamically remove HTML fields based on a Yes/No condition. I've shared the code below for better understanding. If Yes is selected, I want to hide the No Field/Input/Box and vice versa. function AutoCheck() { if (document.getEl ...

What is the solution to the problem of "Failed to execute 'json' on 'Response': body stream already read"?

enter image description here Encountered Issue: Error in processing JSON data in the Response: body stream already read The error mentioned above is a result of issues within your application's code, not due to Cypress. It occurred due to an unhandle ...

Using JQuery: Executing a callback function at the end of each loop following the ajax call

How can I implement a callback for each loop iteration after an AJAX call is completed? Here is my code: Scenario: Suppose I have 3 values - X, Y, Z. Initially, I take the X value, send it to Django views where I use the requests module to retrieve some ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...