Home > front end >  Can someone please explain why is array2 get sorted if I only applied sorting on Array 1 and created
Can someone please explain why is array2 get sorted if I only applied sorting on Array 1 and created

Time:12-28

let array1 = [88,66,33,44,11,67,32,56];
let array2  = new Array(array1);
array1.sort();
console.log(array2);

Created an array1 with random values. Created an array2 using new keyword and initialized it with array1. Sorted array1 and printed out array2. I expected array2 to be unsorted

CodePudding user response:

When new Array is called, a number of things can happen. See here.

  • If no arguments are passed, then an empty array is created.
  • If one argument is passed, and the argument is a number, a new array with a length of that number is created.
  • If one argument is passed, and the argument is not a number, a new array is created, with a single value - that of the passed argument.
  • If multiple arguments are passed, a new array is created, with a value for each argument.

So if you pass a single non-numeric argument, you create a new array with that one argument as a value. Passing an array as the argument results in the creation of an array which has one value, where that value is the passed array.

The value is the passed array itself, not a copy:

const array1 = [88,66,33,44,11,67,32,56];
const array2  = new Array(array1);
console.log(array2[0] === array1);

So when you sort the array (using either reference of array1 or array2[0]), because they reference the same array, you'll see the sorted result no matter which one you examine later.

I expected array2 to be unsorted

Copy the array properly instead. Don't use new Array.

const array2 = [...array1];

CodePudding user response:

The parameters which you pass to the Array constructor are the elements in the new array (unless it's a number).

When you pass array1 to the constructor, it is not cloned. Rather, the array is set as the first item in a new array.

If you want to clone it, you can spread the array, which converts it to a list of parameters from which the Array constructor creates a new array.

let array1 = [88,66,33,44,11,67,32,56];
let array2  = new Array(...array1);
array1.sort();
console.log(array2);

CodePudding user response:

let array2  = new Array(array1);

does not make a copy of array1. It's equivalent to:

let array2 = [array1];

This creates an array whose first element is a reference to the same array as array1.

Any modifications then made to array1 will also affect array2[0], and vice versa.

To make a shallow copy of array1, use:

let array2 = [...array1];
  • Related