0

Need some help in understanding arrays in JS - from some code i just tried below, it appears that they are referenced? Is this correct?

const generatedNumbers = [1, 2, 3, 4, 5];
const shuffleArrayNumbers = shuffleArray(generatedNumbers);

shuffleArrayNumbers.shift();
console.log(shuffleArrayNumbers);
console.log(generatedNumbers);

function shuffleArray(array) {
    return array.sort(() => Math.random() - 0.5);
}

So I was expecting as shuffleArrayNumbers is in its own variable it would behave unique, however that's not the case. The two console.log outputs produce the same output.

Could someone explain what's happening and how I can return a unique/new array.

Thanks.

userMod2
  • 8,312
  • 13
  • 63
  • 115
  • 1
    Arrays are objects. To create a shallow copy, you can use `generatedNumbers.slice()` – Yousaf Jul 26 '22 at 11:36
  • 4
    `.sort()` sorts the array in place AND returns it. See [MDN docs: Array sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). – Peter Krebs Jul 26 '22 at 11:38

2 Answers2

1

The sort method changes the array (MDN: sort).

You can create an independent array with the spread syntax (MDN: spread syntax (...)).

const generatedNumbers = [1, 2, 3, 4, 5];
const shuffleArrayNumbers = shuffleArray(generatedNumbers);

shuffleArrayNumbers.shift();
console.log(shuffleArrayNumbers);
console.log(generatedNumbers);

function shuffleArray(array) {
    return [...array].sort(() => Math.random() - 0.5);
}
tom
  • 9,550
  • 6
  • 30
  • 49
1

Js's Arrays are references so when you do so :

let arr1 = [1, 2 ,3];
let arr2 = arr1;
arr2.pop();
// arr1 = [1, 2] and arr2 = [1, 2]

If you want to avoid this behavior, you have to use copy for exemple by using slice or spread operator :

let arr1 = [1, 2, 3]
let arr2 = arr1.slice();
// or
let arr2 = [...arr1];

arr2.pop();
// arr1 = [1, 2, 3] and arr2 = [1, 2]

Note: This method doesn't work with array of nested object as the object properties will still be a reference.

In this case you have to use structuredClone (no fully supported by browsers https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) :

let arr1 = [1, 2, 3];
let arr2 = structuredClone(arr1);
nem0z
  • 1,060
  • 1
  • 4
  • 17