I'm currently exploring TypeScript and I'm puzzled by the behavior of the code snippet I've shared here: https://codepen.io/anon/pen/EpVMJX. In this code, I noticed that the test array's order changed after I sorted it, even though I stored the result in the 'res' variable. Initially, I thought that the sorting operation automatically modifies the original array. However, I also attempted to create a copy of the original array in a new variable called 'defaultArr' before sorting, and it too changed its order.
let arr:any = [
{ count: 13, year: '1956' },
{ count: 1, year: '1971' },
{ count: 23, year: '1989' },
{ count: 11, year: '1988' }];
let defaultArr = arr;
async function foo(){
console.log(defaultArr);
console.log(arr);
let res = arr.sort((n1,n2)=> n1.count > n2.count? -1:1);
console.log(res);
}
foo();
How can I prevent the original array from changing its order?