0

I have the following error. When I use splice in 1 array, it deletes the element in both arrays. Code:

export class AgendarpacientesComponent implements OnInit {
   arrayPrueba: number[]=[1,2,3,4,5]
}

constructor(){
  this.metodo();
}
ngOnInit() {}

metodo(){
  let arrayAux = this.arrayPrueba;
  arrayAux.splice(1,1);
  console.log(this.arrayPrueba);
}

the result of console log is: [1,3,4,5] and I've used the splice method only on arrayAux. I don't know why this is happening.

Thanks for helping !

1 Answers1

3

You have two references to the same array. Changes made to any reference, affect the same object. Use something like spread operator to make a copy :

let arrayAux = [...this.arrayPrueba];

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Thanks man it worked! I didnt know that operation makes a reference to the same object. Thanks !! – JavierOrellana7 Jul 14 '21 at 08:35
  • It is a simple '=' (assignment operator). That is what it does for objects/arrays etc. For primitive values like strings, numbers you can use it but not for this. – Tushar Shahi Jul 14 '21 at 08:49
  • I get it. What should I do in cases like classes? for ex. i've tried something like this 'let obj= {...this.otherobj}' and if I exec splice method in some array of 'obj', otherobj is affected too. – JavierOrellana7 Jul 14 '21 at 09:16
  • 1
    It aint that simple if your objects are nested. Have a look at this : https://stackoverflow.com/questions/38416020/deep-copy-in-es6-using-the-spread-syntax – Tushar Shahi Jul 14 '21 at 09:18