I want to copy an array and sort it. However, when I copy the array and sort it, it seems to sort both arrays. Does anyone know why this is?
var arr1 = [-1, 2, 0, -2];
var arr2 = [];
arr2 = arr1;
arr2.sort(function(a, b){return a - b});
console.log(arr1);
console.log(arr2);
/*
Expected result:
arr1 = [-1, 2, 0, -2]
arr2 = [-2, -1, 0, 2]
Actual result:
arr1 = [-2, -1, 0, 2]
arr2 = [-2, -1, 0, 2]
*/
I don't know why this is, so it might make a difference that I'm using the p5.js library. I don't know if this matters however. I should also note that I don't know how the sorting algorithm works and I just looked up how to sort numbers on google.
CodePudding user response:
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. Thats why your parent array (arr1) is modified rather the child array (arr2). But if you dont want that to happen replace the following,
arr2 = arr1.slice();