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.
Here are pictures and codes.
3
Answers
Thank you Mr. Nenashev for your quickest advice. My issue has been solved!
The new way to create a deep copy of JS objects is
structuredClone
:But the old way of using
JSON
is still faster sincestructuredClone
has some overhead. If you don’t need features like keeping cross linked objects (which is your case with CSV):There are three ways that come to my mind. Two of them were already mentioned by @alexander-nenashev:
structuredClone
. This is very powerful function but only makes sense for complex non-JSON structures (e.g. Sets, Maps etc.)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.