Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone please explain why is array2 get sorted if I only applied sorting on Array 1 and created array2 as a NEW array? This is javascript

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading