JavaScript: How to Duplicate Multidimensional Arrays

I am looking to create a duplicate of a multidimensional array in order to experiment with the cloned array without impacting the original array.

Here is the function I am currently using for this purpose:

Array.prototype.clone = function () { 
   var newArray = new Array(this.length);
     for(var i=0; i < this.length; i++ ){
        newArray[i] = this[i];
   }
   return newArray;
};

The issue with this approach is that it clones all arrays due to its usage of the array prototype. Can anyone suggest a better way to achieve this?

Answer №1

vsync is absolutely correct, my initial response did not account for the scenario var a = [[1,2],[3,4]];
With that in mind, here is an enhanced and revised solution

var a = [[1,2],[3,4]];
Array.prototype.clone = function() {
    var arr = this.slice(0);
    for( var i = 0; i < this.length; i++ ) {
        if( this[i].clone ) {
            //recursive process
            arr[i] = this[i].clone();
        }
    }
    return arr;
}

var b = a.clone()

console.log(a);
console.log(b);

b[1][0] = 'a';

console.log(a);
console.log(b);

//[[1, 2], [3, 4]]
//[[1, 2], [3, 4]]
//[[1, 2], [3, 4]]
//[[1, 2], ["a", 4]]

Answer №2

To solve this problem, implementing recursion is essential

let numbers = [1, 2, [3, 4, [5, 6]]];

Array.prototype.copy = function() {
    let newArray = [];
    for(let j = 0; j < this.length; j++) {
        if(this[j].copy) {
            //recursive call
            newArray[j] = this[j].copy();
            break;
        }
        newArray[j] = this[j];
    }
    return newArray;
}

let copiedNumbers = numbers.copy();

console.log(numbers);
console.log(copiedNumbers);

copiedNumbers[2][0] = 'a';

console.log(numbers);
console.log(copiedNumbers);

/*
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, ["a", 4, [5, 6]]]
*/

However, keep in mind that any other objects within the original array will be duplicated by reference

Answer №3

I have discovered an alternative approach that outperforms meouw's method:

var source = [
  [1, 2, {c:1}],
  [3, 4, [5, 'a']]
];

// Extending "Array" primitive prototype with a new method:
Array.prototype.clone = function() {
  function isArr(elm) {
    return String(elm.constructor).match(/array/i) ? true : false;
  }

  function cloner(arr) {
    var arr2 = arr.slice(0),
        len = arr2.length;

    for (var i = 0; i < len; i++)
      if (isArr(arr2[i]))
        arr2[i] = cloner(arr2[i]);

    return arr2;
  }
  return cloner(this);
}

// Cloning the array
var copy = source.clone();

// Modifying the copied array
copy[0][0] = 999;

console.dir(source);
console.dir('**************');
console.dir(copy);

Another method that is capable of working exclusively with datasets containing primitive values (String, Numbers, Objects):

var source = [
  [1,2, {a:1}],
  ["a", "b", ["c", 1]]
];

// Cloning the "source" Array
var copy = JSON.parse(JSON.stringify(source));

// Modifying the copied array
copy[0][0] = 999;

// Displaying both arrays
console.dir(copy)
console.log('***********')
console.dir(source)

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

Include a fresh attribute to a current JSON within a FOR loop

My goal is to populate a bootstrap-carousel using a more detailed JSON file pulled from a database. To illustrate, here is an example of my old JSON structure: old.json [ {"screen": [{ "img" : "../static/images/product/34.jpg", "price": "Rs 100", ...

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Executing a nested function as an Onclick event in an HTML document

I am currently working on a project within the Phone Gap framework where I need to transfer values from one HTML page to another. My solution involved using the code snippet below. var searchString = window.location.search.substring(1),i, val, params = s ...

Tips for updating the chosen value with jquery or javascript

I am facing a situation where I need to change the selected option in a dropdown menu using a function triggered onClick later in the application. <select id="myselect"> <option value=aa>aa</option> <option value=bb>bb</option&g ...

Cannot access elements of a value type [String] using an NSNumber index?

I am facing an issue where I am trying to link an image's name to a button. The image name is saved in an array, but the code returns an error as mentioned in the title. Here is my current code snippet: //profilePic represents the button //friend is ...

Using Node.js and TypeScript to define custom data types has become a common practice among developers

I offer a variety of services, all yielding the same outcome: type result = { success: boolean data?: any } const serviceA = async (): Promise<result> => { ... } const serviceB = async (): Promise<result> => { ... } However, th ...

Execute a Jquery function on every field

I need to capitalize each value of the select options that come from a SQL database. However, the code provided only works on the first field... function capitalize(str){ var text = str.text().replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCas ...

What are the recommended guidelines for using TypeScript effectively?

When facing difficulties, I have an array with functions, such as: this._array = [handler, func, type] How should I declare this private property? 1. Array<any> 2. any[] 3. T[] 4. Array<T> What is the difference in these declarations? ...

Using the forEach method, we can create multiple buttons in ReactJS and also access the onClick handler

I have a button with both the label and onClick properties. Additionally, I have an array containing the values I need to assign to the label property. Here is the code snippet: render(){ {tabel_soal.forEach(function (item, index) { <Ra ...

Ways to efficiently populate HTML elements with JSON data

I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi a ...

Ways to verify if the scroll bar of a user is not visible

Is there a method to detect if the user has forcibly hidden the scroll bar in the operating system? 1. Automatically based on mouse or trackpad 2. Always 3. When scrolling I want to adjust the width of an HTML element if the scroll bar is visible, which c ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...

Passing variable values from .post response to PHP: A guide

I'm currently working on integrating Geocode from the Google Maps API into my WordPress plugin within the wp-admin. I have created a custom post type that includes an input field for the address of a place, and I also have jQuery code set up to watch ...

What is the process for creating a 3D scene using an SVG image?

Recently, I came across an SVG image that caught my eye: https://i.sstatic.net/hTsA1.png Now, I am looking to recreate a similar image like this: https://i.sstatic.net/JWrjz.png Any ideas on how I could achieve this using three.js or another JavaScript 3 ...

How to keep text always locked to the front layer in fabric.js without constantly bringing it to the front

Is it possible to achieve this functionality without using the following methods? canvas.sendBackwards(myObject) canvas.sendToBack(myObject) I am looking to upload multiple images while allowing them to be arranged forward and backward relative to each o ...

"Enhance Your Website with Dynamic List Item Animations in

Working on a simple animation involves removing classes from list items once they are loaded and added to the document. However, I am encountering issues with the animation execution. I aim for a stepped animation pattern as depicted below... https://i.ss ...

Deleting a record in MongoDB based on a specific value present in a column

I am in search of more information about delete triggers in MongoDB. Source: Query on MongoDB Delete Triggers I am interested in converting DELETE operations to UPDATE + AUTOMATIC DELETE. To achieve this, I plan to introduce a new field called "flag" ...

What is the best way to incorporate a .json configuration into the environment.ts file and access an API with Angular

I need to import a Json file from the assets folder containing URLs like the following: config.json: { "url1": "https://jsonplaceholder.typicode.com/posts", "url2" : "https://reqres.in/api/users", ...

manipulating arrays in Python

Struggling to make the self.value work without errors, aiming to loop through self.a, self.b, self.c. Seeking help in learning how to achieve desired output x = [AA, EE, II] using classes and loops. Attempted a for loop but still new to Python and object ...