Javascript Array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Javascript Array

I want to copy a two dimensional array by value, not by reference. I tried "var arr2 = arr1.slice();" but it didn't work. When I do this for example, it changes arr1 and arr2. var arr1 =[[1,2], [3,4]]; var arr2 = [arr1[0], arr1[1]]; arr2[0][1]=5; So my question is: How do I copy a two dimensional array by value in Javascript?

3rd May 2017, 2:48 PM
Tim G
Tim G - avatar
7 Answers
+ 9
@tim Since, array is not a basic data type every element contains a reference In case of array of arrays. So you need to do like this I guess: https://code.sololearn.com/WMAbJHh5SAK9/?ref=app
3rd May 2017, 3:06 PM
Ashwani Kumar
Ashwani Kumar - avatar
+ 6
arr1.slice() will work. You have used I guess arr1.splice()
3rd May 2017, 2:54 PM
Ashwani Kumar
Ashwani Kumar - avatar
+ 6
@Ashwani thank you very much! @Mohammad, change "arr2[0]" to "arr2[0][0]" then you see what I mean :-|
3rd May 2017, 3:12 PM
Tim G
Tim G - avatar
+ 5
Example code in playground please
3rd May 2017, 2:56 PM
Tim G
Tim G - avatar
+ 4
@Tim, it seems slice() also use reference for inner array. However you can use a little trick here. first convert the arr1 to string then convert it back to a new array and assign it to arr2 variable. Check out the updated code.. https://code.sololearn.com/Wm9VYi97J2VB/?ref=app
3rd May 2017, 3:30 PM
Apel Mahmod
Apel Mahmod - avatar
+ 3
Use slice() method like this, var arr2 = arr1.slice()
3rd May 2017, 2:55 PM
Apel Mahmod
Apel Mahmod - avatar
3rd May 2017, 3:04 PM
Apel Mahmod
Apel Mahmod - avatar