0

Newbie here

I recently encounter a problem while using the array.splice method to delete elements from a list. The code is similar to this

var A = [0,1,2,3,4,5];
var B = A;
B.splice(3,1)
console.log(B) //returns [ 0, 1, 2, 4, 5 ]
console.log(A) //returns [ 0, 1, 2, 4, 5 ]

Somehow, splicing B splices A as well.

I tried to make my own function to delete an element. Same problem.

var deleteElement = function(array,index){
  var array2=array;   
  for(i=index;i<array2.length;i++){ 
    array2[i]=array2[i+1]    
  }
  array2.pop();
  return array2;
}
  var A = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
  var B = deleteElement(A,4)
  
  console.log(A) //returns [ 0, 1, 2, 3, 5, 6, 7 ]
  console.log(B) //returns [ 0, 1, 2, 3, 5, 6, 7 ]   

I have no idea why A is being altered by altering B. Any help would be greatly appreciated.

2 Answers2

1

"Somehow" Arrays are mutative, B is a reference to A. Alter B, you alter A. You need to make a clone that isn't a reference.

const a = [1,2,3,4,5];
const b = a.slice(0);
//b is a copy of a with no reference

b.splice(3,1);
console.log(b);
console.log(a);
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
0
var A = [0,1,2,3,4,5];
var B = A.slice(0);
B.splice(3,1)
console.log(B)
console.log(A)

Go through the deep copy and shallow copy in javascript.