0

I have an array (arr1) that I push into another (arr2). I modify 'arr1' with a loop, but in the end, 'arr2' is also modified ! Why ? I would like to keep 'arr2' the same at the start. What is my mistake ?

arr1 = [1,2,3];
arr2 = [];
          
arr2.push(arr1);
              
$("#a1").html(arr1); // 1,2,3
$("#a2").html(arr2); // 1,2,3   

    // loop modifying ONLY 'arr1'... 
    for (i=0 ; i<arr1.length ; i++) {
        arr1[i] = arr1[i]*3;
    }

$("#b1").html(arr1); // 3,6,9
$("#b2").html(arr2); // 3,6,9 ... ??..incomprehensible !
// 'arr2' should not be modified ! The result should be 1,2,3
// Why is 'arr2' still modified ?
  • 1
    Pushing an array into another array does not make a copy of the original array. All you are doing is making one of the elements in the array point to the same array in memory. Any changes made to the sub array will be reflected in the parent array, because they both point to the same memory space. – Taplar Aug 25 '20 at 17:15
  • All right, I understood. Clear answer ... Thanks and sorry for the [duplicate], I will look better next time... :-) – BLUELIGHT BLUELIGHT Aug 25 '20 at 17:35

1 Answers1

1

array object act as reference type, instead of arr2.push(arr1); you can try latest es6 spread operator arr2 = [...arr1]; Otherwise slice method arr2 = arr1.slice();.

Siva Rm K
  • 284
  • 1
  • 6