I have encountered an issue while working with arrays. I am initializing two arrays - one with some values and another as empty. However, when I assign the items from the first array to the second array and then clear the first array, it unexpectedly clears the second array as well.
My Code:
array1: any = [1, 2, 3, 4, 5];
array2: any = [];
ngOnInit() {
this.array2 = this.array1;
this.array1.length = 0;
console.log('I cleared Array1');
console.log(this.array1);
console.log('Array2 Clears Automatically');
console.log(this.array2);
}
Here is a Stackblitz sample demonstrating the issue: https://stackblitz.com/edit/angular-yfhdi3?file=src%2Fapp%2Fapp.component.ts
I need to find a solution to prevent the second array (array2) from losing its value after assignment, as I plan to perform operations on it later in the code.