skip to Main Content

Could you help me copy a 2-D array when you use JavaScript?
Currently, I understand that the assign like ‘array2 = array1’ does not work, because both arrays will have the same value when either of them let its value change.
So, I used Object.create() so that two 2-d arrays would be totally different.

console.log("Hiiiii");

let randnum = Math.floor( Math.random() * 100 );

// Create a shift-jis-loading csv instance
let csv = new XMLHttpRequest();
csv.overrideMimeType("text/plain; charset=shift_jis");
 
// Open a csv file
csv.open("GET", "./csvfile/Word_List_1.csv", false);
 
// In case of failures of csv loading
try {
  csv.send(null);
} catch (err) {
  console.log(err);
}
 
// Define an array
let csvArray = [];
 
// Process toward an Array csvArray
let lines = csv.responseText.split(/rn|n/);
 
// Proceed with each line
for (let i = 0; i < lines.length; ++i) {
  let cells = lines[i].split(",");
  if (cells.length != 1) {
    csvArray.push(cells);
  }
}

// Remove the last value of each row
csvArray.map((row)=>{
  row.pop()
})
 
// コンソールに配列を出力
// console.log(csvArray[randnum][0]);
// console.log(csvArray[randnum][1]);

console.log(csvArray);


console.log("before copy");
console.log(csvArray[0][0]);

// Copy the csvArray
let cloneArray = Object.create(csvArray);

// Check whether each value will be different
cloneArray[0][0]="testMan";

// The result is that both the value is the same: "testMan"
console.log(csvArray[0][0]);
console.log(cloneArray[0][0]);  

I would be very grateful if you could kindly show an example of copying 2-d arrays.

enter image description here

Here are pictures and codes.

3

Answers


  1. Chosen as BEST ANSWER

    Thank you Mr. Nenashev for your quickest advice. My issue has been solved!


  2. The new way to create a deep copy of JS objects is structuredClone:

    let cloneArray = structuredClone(csvArray);
    

    But the old way of using JSON is still faster since structuredClone has some overhead. If you don’t need features like keeping cross linked objects (which is your case with CSV):

    let cloneArray = JSON.parse(JSON.stringify(csvArray));
    
    Login or Signup to reply.
  3. There are three ways that come to my mind. Two of them were already mentioned by @alexander-nenashev:

    1. Using structuredClone. This is very powerful function but only makes sense for complex non-JSON structures (e.g. Sets, Maps etc.)
    2. Using JSON.parse + JSON.stringify. This is quite fast and simple way of doing deep copy but it’s restricted to JSON-like structures – Arrays and Objects.
    3. Doing manual copy. Although this is quite cumbersome for any non trivial object, for simple arrays it would be the fastest approach.
    const newArray = [];
    oldArray.forEach((row, i) => {
      newArray.push([]);
      row.forEach((cell) => newArray[i].push(cell));
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search